Invalid Model State with ViewModel - C# ASP.NET CORE - c#

Hopefully a basic question, I've created a "Create" page for Contacts which creates a list of all Customers in the system. I use a ViewModel to do this and this has been fine. However now on the Customers model I've assigned the CustomerName field to be Required it's causing a ModelState.IsValid to be false, and I cannot figure out why.
Customer
public class Customer
{
public int CustomerId { get; set; }
[Required]
[Display(Name = "Customer Name")]
public string? CustomerName { get; set; }
public ICollection<Contact> Contacts { get; set; }
public ICollection<Job> Jobs { get; set; }
}
Contact
public class Contact
{
public int ContactId { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }
public string Telephone { get; set; }
public Customer Customer { get; set; }
}
ViewModel
public class ContactDetailViewModel
{
public Contact Contact { get; set; }
public Customer Customer { get; set; }
public List<SelectListItem> Customers { get; set; }
}
Form
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Contact.FirstName" class="control-label"></label>
<input asp-for="Contact.FirstName" class="form-control" />
<span asp-validation-for="Contact.FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.LastName" class="control-label"></label>
<input asp-for="Contact.LastName" class="form-control" />
<span asp-validation-for="Contact.LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.EmailAddress" class="control-label"></label>
<input asp-for="Contact.EmailAddress" class="form-control" />
<span asp-validation-for="Contact.EmailAddress" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.Telephone" class="control-label"></label>
<input asp-for="Contact.Telephone" class="form-control" />
<span asp-validation-for="Contact.Telephone" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Customer.CustomerName" class="control-label"></label>
<select class="form-control dropdown" asp-for="Customer.CustomerId" asp-items="#Model.Customers">
<option></option>
</select>
<span asp-validation-for="Customer.CustomerId" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
Controller
public async Task<IActionResult> Create([Bind("ContactId,FirstName,LastName,EmailAddress,Telephone")] Contact contact, ContactDetailViewModel contactDetailViewModel)
{
contact.Customer = await _context.Customers.FirstOrDefaultAsync(c => c.CustomerId == contactDetailViewModel.Customer.CustomerId);
//Has to be a better way of doing this??? Why is it faling without... 06/03/2021
//ModelState.Remove("Customer.CustomerName");
if (ModelState.IsValid)
{
_context.Add(contact);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(contact);
}
If I don't include ModelState.Remove("Customer.CustomerName"); then it doesn't work. However I don't want to be doing anything with the CustomerName as I just want to update the Contact.Customer to be the "new" selected customer.
Thanks!

You have the error in your class. Add CustomerId to Contact:
public class Contact
{
public int ContactId { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }
public string Telephone { get; set; }
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
and fix the view:
<div class="form-group">
<label asp-for="Customer.CustomerName" class="control-label"></label>
<select class="form-control dropdown" asp-for="Contact.CustomerId" asp-items="#Model.Customers">
<option></option>
</select>
<span asp-validation-for="Contact.CustomerId" class="text-danger"></span>
</div>
and you can fix action too:
contact.Customer = await _context.Customers.FirstOrDefaultAsync(c => c.CustomerId == contactDetailViewModel.Contact.CustomerId);
but it is a reduntant code. You don't need this code at all, since you can save Contact without this.
and you need to fix the binding too by adding CustomerId:
public async Task<IActionResult> Create([Bind("ContactId, CustomerId, FirstName,LastName,EmailAddress,Telephone")] Contact contact, ContactDetailViewModel contactDetailViewModel)
and by the way you include the whole Customer in the model only for
<label asp-for="Customer.CustomerName" class="control-label"></label>
you can leave Customer property null and use this code:
<label asp-for="Contact.CustomerId" class="control-label"> Customer </label>

Related

validation in the collection class not working

I have the following Model:
public partial class EmployeeInfo
{
public int EmployeeInfoId { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; } =null!;
public virtual ICollection<EmergencyInfo> EmergencyInfos { get; } = new List<EmergencyInfo>();
}
I have another Model class for EmergencyInfo
public partial class EmergencyInfo
{
public int EmergencyInfoId { get; set; }
public int EmployeeInfoId { get; set; }
[DisplayName("First Name")]
[Required]
public string? FirstName { get; set; } = null!;
public virtual EmployeeInfo? EmployeeInfo { get; set; }
}
Although the Firstname is required in EmergencyInfo Model. When I click the submit button, it does not show that Firstname is required . It does show that LastName is required because that field exists in the EmployeeInfo model. below is my razor page:
#model AckPackage.Models.EmployeeInfo
#{
ViewData["Title"] = "Create";
}
<div class="form-group row">
<div class="col-sm-4">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control input-lg" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="col">
<label asp-for="#Model.EmergencyInfos.ToList()[i].FirstName" class="control-label"></label>
<input name="EmergencyInfos[#i].FirstName" value="#(string.IsNullOrEmpty(Model.EmergencyInfos.ToList()[0].FirstName)? "": #Model.EmergencyInfos.ToList()[0].FirstName)" class="form-control" />
<span asp-validation-for="#Model.EmergencyInfos.ToList()[0].FirstName" class="text-danger"></span>
</div>
#section Scripts {
#{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
Lastname not filled always displays LastName is required, but Firstname from emergencyInfo always goes to HTTPPost without showing validation error message.
If I remove tolist() as suggested in the comment below then I get this compilation error:
Be sure asp-for tag helper for input like below:
<div class="col">
<label asp-for="#Model.EmergencyInfos.ToList()[0].FirstName" class="control-label"></label>
<input asp-for="EmergencyInfos.ToList()[#i].FirstName" name="EmergencyInfos[#i].FirstName"value="#(string.IsNullOrEmpty(Model.EmergencyInfos.ToList()[0].FirstName)? "": #Model.EmergencyInfos.ToList()[0].FirstName)" class="form-control" />
<span asp-validation-for="#Model.EmergencyInfos.ToList()[0].FirstName" class="text-danger"></span>
</div>

ASP.NET MVC User ID Link with other Tables

I am working on a Data Entry system for storing users financial data. Each user will enter his Revenues and Expenses each in a table.
The tables were designed as follows:
Primary Key: Rev/Exp ID
Foreign Key: Organization ID
This is a sample for my models:
public class Revenue
{
[Key]
public int RevenueId { get; set; }
public int Year { get; set; }
public double Source1 { get; set; } = 0;
public double Source2 { get; set; } = 0;
public double Source3 { get; set; } = 0;
public double Source4 { get; set; } = 0;
// Foreign Key Relationship
public string OrganizationId{ get; set; }
public virtual Organization Organization{ get; set; }
}
public class Organization
{
public virtual ICollection<Revenue> Revenues { get; set; }
public virtual ICollection<Expense> Expenses { get; set; }
}
This is the DBContext:
public class AppDbContext : IdentityDbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
// Create tables in DB
public DbSet<Organization > Organization { get; set; }
public DbSet<Revenue> Revenue { get; set; }
public DbSet<Expense> Expense { get; set; }
}
Here is the Create Action in the Controller:
// GET: Revenue/Create
public IActionResult Create()
{
return View();
}
// POST: Revenue/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("RevenueId,Year,Source1,Source2,...,OrganizationId")] Revenue revenue)
{
if (ModelState.IsValid)
{
_context.Add(revenue);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["OrganizationId"] = new SelectList(_context.OrganizationId, "Id", "Id", revenue.OrganizationId);
return View(revenue);
}
Finally, Create View:
#using Microsoft.AspNetCore.Identity
#inject SignInManager<IdentityUser> SignInManager
#inject UserManager<IdentityUser> UserManager
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Revenue</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Year" class="control-label"></label>
<input asp-for="Year" class="form-control" />
<span asp-validation-for="Year" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Source1" class="control-label"></label>
<input asp-for="Source1" class="form-control" />
<span asp-validation-for="Source1" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Source2" class="control-label"></label>
<input asp-for="Source2" class="form-control" />
<span asp-validation-for="Source2" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Source3" class="control-label"></label>
<input asp-for="Source3" class="form-control" />
<span asp-validation-for="Source3" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Source4" class="control-label"></label>
<input asp-for="Source4" class="form-control" />
<span asp-validation-for="Source4" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrganizationId" class="control-label"></label>
<input asp-for="OrganizationId" class="form-control" value="#UserManager.GetUserId(User)"/>
<span asp-validation-for="OrganizationId" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
So, after a lot of search I was able to capture user ID with UserManager and assigning it to a hidden field, then sending it with the form. However, that did not work, the form is not submitting and no error messages are displayed neither.
Is this is a correct way of capturing user ID as a Foreign Key and how to fix the Create Action ?
You didn't really specify anything about your authentication. If you are using typical ASP.Net authentication, you can probably use User.Identity.Name, like this:
if (ModelState.IsValid)
{
revenue.UserId = User.Identity.Name
_context.Add(revenue);
...
As from .NET 6, in order to assign an attribute in a model to be Nullable the ? should be added after the name of the attribute, otherwise it is required.
The problem was that the UserId is passed but the User object is null (which should be because it is just a reference).
So the model should be:
public class Revenue
{
[Key]
public int RevenueId { get; set; }
public int Year { get; set; }
public double Source1 { get; set; } = 0;
public double Source2 { get; set; } = 0;
public double Source3 { get; set; } = 0;
public double Source4 { get; set; } = 0;
// Foreign Key Relationship
public string OrganizationId{ get; set; }
public Organization? Organization{ get; set; }
}
And the view will be as is by passing user ID in a hidden field that we got from UserManager.

Foreign Key not showing in dropdown box | MVC

I'm somewhat new to MVC and have been following along with a tutorial but it has no answers regarding my question. For my Create page, the Foreign keys are not showing up. Basically, on the Projects page I created a project, on the People page I created a person. So when I try to create a ProjectRole on the ProjectRoles page, the ProjectId and PersonId are not showing up in the drop-down menu. Down below all of my code, I have provided a screenshot of what I have tried to put into words.
My models:
public class Project
{
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string Name { get; set; }
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime DueDate { get; set; }
public ICollection<ProjectRole> ProjectRoles { get; set; }
}
public class Person
{
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string FirstName { get; set; }
[Required]
[MaxLength(30)]
public string MiddleName { get; set; }
[Required]
[MaxLength(30)]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
public ICollection<ProjectRole> ProjectRoles { get; set; }
}
public class ProjectRole
{
public int Id { get; set; }
[Required]
public double HourlyRate { get; set; }
[ForeignKey("Person")]
public int PersonId { get; set; }
[ForeignKey("Project")]
public int ProjectId { get; set; }
[ForeignKey("AppRole")]
public int RoleId { get; set; }
}
My Controller code:
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,HourlyRate,PersonId,ProjectId,RoleId")] ProjectRole projectRole)
{
if (ModelState.IsValid)
{
_context.Add(projectRole);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(projectRole);
}
And my view code here:
#model Project2.Models.Entities.ProjectRole
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>ProjectRole</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="HourlyRate" class="control-label"></label>
<input asp-for="HourlyRate" class="form-control" />
<span asp-validation-for="HourlyRate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PersonId" class="control-label"></label>
<select asp-for="PersonId" class ="form-control" asp-items="ViewBag.PersonId"></select>
</div>
<div class="form-group">
<label asp-for="ProjectId" class="control-label"></label>
<select asp-for="ProjectId" class ="form-control" asp-items="ViewBag.ProjectId"></select>
</div>
<div class="form-group">
<label asp-for="RoleId" class="control-label"></label>
<input asp-for="RoleId" class="form-control" />
<span asp-validation-for="RoleId" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Screenshot of example of what I mean:
I suppose more personable to display the Person Name (and the Project Name) in the select controls, but to pass the PersonId (and ProjectId) to the Create method when click on the Create button.
Therefore, prepare the Person list (and the Project list) like below:
public IActionResult Create()
{
var persons = new List<SelectListItem>();
// Iterate through `Persons`
foreach(var p in _context.Persons)
{
persons.Add(new SelectListItem() { Value= p.Id, Text = p.FirstName+", "+p.LastName});
}
ViewBag.Persons = persons;
// Prepare the projects list (like `Persons` list above)
// ... your code here
ViewBag.Projects = persons;
return View(new ProjectRole(){ /* Add your code here to create the ProjectRole .../* });
}
And in the view:
<div class="form-group">
<label asp-for="PersonId" class="control-label"></label>
<select asp-for="PersonId" class="form-control" asp-items="ViewBag.Persons"></select>
</div>
<div class="form-group">
<label asp-for="ProjectId" class="control-label"></label>
<select asp-for="ProjectId" class="form-control" asp-items="ViewBag.Projects"></select>
</div>
For additional information see The Select Tag Helper
*NOTE: And I would recommend to create compound view model to include all required information. *
ViewModels or ViewBag?
Understanding Best Way to Use Multiple Models in ASP.NET MVC

creating category and subcategory dependent list box using asp.net core 2.2

I am trying a create a page where I have a form to create the product. here I trying to creating category and subcategory dependent list box.but not understand how I will do that.
Here is my code:
public class Category
{
public int Id { get; set; }
[Required]
[Display(Name = "Category Name")]
public string CategoryName { get; set; }
}
//my SubCategory model
public class SubCategory
{
public int Id { get; set; }
[Required]
[Display(Name = "SubCategory Name")]
public string SubCategoryName { get; set; }
}
//my product model
public class Product
{
public int Id { get; set; }
[Required]
public String Name { get; set; }
[Required]
[Display(Name = "Category Type")]
public int CategoryTypeId { get; set; }
[ForeignKey("CategoryTypeId")]
public Category Category { get; set; }
[Required]
[Display(Name = "SubCategory Type")]
public int SubCategoryTypeId { get; set; }
[ForeignKey("SubCategoryTypeId")]
public SubCategory SubCategory { get; set; }
}
Product Controller
[HttpGet]
public IActionResult Create()
{
ViewData["CategoryId"] = new SelectList(_db.Category.ToList(), "Id", "CategoryName");
ViewData["SubCategoryId"] = new SelectList(_db.SubCategory.ToList(), "Id", "SubCategoryName");
return View();
}
[HttpPost]
public async Task<IActionResult> Create(Product product)
{
if (ModelState.IsValid)
{
_db.Product.Add(product);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(product);
}
Create.cshtml
#model Amazon.Models.Product
#{
ViewData["Title"] = "Create";
}
<br />
<h2 class="text-info">Add New Product</h2>
<form asp-action="Create" method="post" enctype="multipart/form-data">
<div class="p-4 rounded border">
<div asp-validation-summary="ModelOnly" class="text-danger">
</div>
<h3>#ViewBag.message</h3>
<div class="form-group row">
<div class="col-2">
<label asp-for="Name"></label>
</div>
<div class="col-5">
<input asp-for="Name" class="form-control" />
</div>
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="CategoryTypeId"></label>
</div>
<div class="col-5">
<select asp-for="CategoryTypeId" asp-items="ViewBag.CategoryId" class="form-control"></select>
#*<input asp-for="ProductTypeId" class="form-control" />*#
</div>
<span asp-validation-for="CategoryTypeId" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="SubCategoryTypeId"></label>
</div>
<div class="col-5">
<select asp-for="SubCategoryTypeId" asp-items="ViewBag.SubCategoryId" class="form-control"></select>
#*<input asp-for="SpecialTagId" class="form-control" />*#
</div>
<span asp-validation-for="SubCategoryTypeId" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Save" />
<a asp-action="Index" class="btn btn-success">Back To List</a>
</div>
</div>
</form>
#section Scripts{
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
above code, I did successfully data-bind of my product controller and view.but I trying to creating category and subcategory dependent list box.but not understand how I will do that.
here my expectation output :
I am an absolute beginner. please help anyone.
I trying to creating category and subcategory dependent list box.
To implement cascading dropdown for Category and Subcategory, as I mentioned in comment, you can populate SubCategory dropdown based on the previous selection of Category in Category dropdown change event, like below.
You can try to modify your model class and implement one-to-many relationship between Category and Subcategory entities, so that you can store data like below in database and retrieve all sub-categories based on the provided CategoryId.
Populate only Category dropdown when page loads
<div class="form-group">
<div class="col-2">
<label asp-for="CategoryTypeId" class="control-label"></label>
</div>
<div class="col-5">
<select asp-for="CategoryTypeId" asp-items="ViewBag.CategoryId" class="form-control">
<option value="">Select Category</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-2">
<label asp-for="SubCategoryTypeId" class="control-label"></label>
</div>
<div class="col-5">
<select asp-for="SubCategoryTypeId"></select>
</div>
</div>
Dynamically populate SubCategory dropdown in Category dropdown change event
$(function () {
$("select#CategoryTypeId").change(function () {
var cid = $(this).val();
$("select#SubCategoryTypeId").empty();
$.getJSON(`/Home/GetSubCategory?cid=${cid}`, function (data) {
//console.log(data);
$.each(data, function (i, item) {
$("select#SubCategoryTypeId").append(`<option value="${item.id}">${item.name}</option>`);
});
});
})
});
Action method GetSubCategory
public IActionResult GetSubCategory(int cid)
{
var SubCategory_List=_db.SubCategory.Where(s => s.CategoryId == cid).Select(c => new { Id = c.Id, Name = c.SubCategoryName }).ToList();
return Json(SubCategory_List);
}
Test Result
Update:
Model classes
public class Category
{
public int Id { get; set; }
[Required]
[Display(Name = "Category Name")]
public string CategoryName { get; set; }
public ICollection<SubCategory> SubCategories { get; set; }
}
public class SubCategory
{
public int Id { get; set; }
[Required]
[Display(Name = "SubCategory Name")]
public string SubCategoryName { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
}

Displaying dropdownlistfor from database

What I'm trying to do--
I have two different database tables (CabinetI, AdminCabinetI). AdminCabinetI has populated data(Column name ItemID) that has to be displayed to users as a dropdownlist. Once users fill out other information, make selections from the dropdownlist and hit the submit button, that data goes to CabinetI.
When I add Dropdownlistfor, it starts throwing an error. I've tried a lot of different ways, but nothing worked. So at this point, I would like to show my code and see what I've done wrong.
This is my ViewModel --
public class MultipleViews
{
public Note note { get; set; }
public AdminCabinetI admincabinetI { get; set; }
public CabinetI cabineti { get; set; }
public IEnumerable<AdminCabinetI> SelectSerialsI { get; set; }
}
This is my Models (AdminCabinetI) and (CabinetI) --
public class AdminCabinetI
{
[Key]
public int ItemNo { get; set; }
[Required(ErrorMessage = "Please enter item title")]
public string ItemName { get; set; }
[Required(ErrorMessage = "Please enter Item Serial number/ID")]
public string ItemID { get; set; }
[Required(ErrorMessage = "Please select cabinet status")]
public string ItemStatus { get; set; }
public string BA { get; set; }
public string Printer { get; set; }
}
public class CabinetI
{
[Key]
public int CabinetNo { get; set; }
[Required]
public string CabinetName { get; set; }
[Required]
public string Department { get; set; }
[Required(ErrorMessage = "Please enter your name")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please select one of cabinet serial numbers")]
public string CabinetSerial { get; set; }
[Required(ErrorMessage = "Please select cabinet status")]
public string CabinetStatus { get; set; }
[Required(ErrorMessage = "Please type specify cabinet location")]
public string CabinetLocation { get; set; }
}
And this is my View --
#model PreMode.ViewModels.MultipleViews
<div class="form-group">
<label>Category</label>
<input type="text" readonly="readonly" class="form-control" style="opacity: 0.6" value="I2" asp-for="cabineti.CabinetName">
</div>
<div class="form-group">
<label>Department</label>
<select class="form-control" asp-for="cabineti.Department">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" asp-for="cabineti.UserName" placeholder="Please enter your name" />
<span class="text-danger" asp-validation-for="cabineti.UserName"></span>
</div>
<div class="form-group">
<label>Serial Number</label>
#Html.DropDownListFor(model => model.admincabinetI, new SelectList(Model.admincabinetI.ItemID, "ItemID"), "Select Cabinet Serial #", new { #class = "form-control" })
</div>
<div class="form-group">
<label>Status</label>
<select class="form-control" asp-for="cabineti.CabinetStatus">
<option value="In Use">In Use</option>
<option value="Not In Use">Not In Use</option>
<option value="Testing">Testing</option>
</select>
<span class="text-danger" asp-validation-for="cabineti.CabinetStatus"></span>
</div>
<div class="form-group">
<label>Location</label>
<input type="text" class="form-control" asp-for="cabineti.CabinetLocation" placeholder="Please type current location of the cabinet" />
<span class="text-danger" asp-validation-for="cabineti.CabinetLocation"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Checkout</button>
<a class="btn btn-warning" href="/Cabinet/MainCabinetI">Cancel</a>
</div>
</form>
And this is my Controller--
public IActionResult GetDropDown()
{
if (ModelState.IsValid)
{
using (var db = new DataMigration())
{
var CabinetSerialsI = db.AdminCabinetI.ToList();
var viewModel = new MultipleViews
{
SelectSerialsI = CabinetSerialsI
};
return View(viewModel);
}
}
return View();
}
SelectList doesn't have an overload method that matches your intentions. In HTML land a select element has both values and descriptions, similar to a KeyValuePair. In your case both the key and value are the same. To account for that, try:
SelectList(Model.admincabinetI.ItemID, "ItemID", "ItemID")
Add a constructor to the MultipleViews class and set the variables such as this
public MultipleViews()
{
this.Note = new Note();
this.AdminCabinetI = new AdminCabinetI ();
this.CabinetI = new CabinetI ();
this.SelectSerialsI = new List<AdminCabinetI>();
}
You had not declared the variables before you set their value.

Categories

Resources