Reputation: 1795
I have a model. This model look like this:
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public List<Category> Parent { get; set; }
In the add action I populate Parent:
public ViewResult Add()
{
var addCategoryModel = new CategoryEditModel
{
Parent = Mapper.Map<List<Category>>(_productRepository.Categories.ToList())
};
return View("add", addCategoryModel);
}
When I submit the form my model state always is invalid, because my selected value in DropDownList "..is invalid." I made something wrong. What is the correct way to do this?
Upvotes: 0
Views: 1288
Reputation: 643
I've had some hard times with drop downs and helpers for them in MVC too. I finally have adopted the following approach as my way:
In my view model I create:
public List<SelectListItem> employeeList;
public int SelectedItemID;
Typically would have a get for populating the drop down via the database/Entity Framework:
public IEnumerable<SelectListItem> employeeList
{
get
{
return new SunGardDBEntities()
.employees
.OrderBy(e => e.employeeFName)
.ToList()
.Select(e => new SelectListItem { Text = e.employeeFName + " " + e.employeeLName, Value = e.employeeID.ToString() });
}
}
And in my .cshtml file I then say:
@Html.DropDownListFor(model => model.SelectedItemID, new SelectList(Model.employeeList, "Value", "Text"), new Dictionary<string, object> { { "data-placeholder", "Choose a sandbox..." }, { "class", "chzn-select" }, { "style", "width:200px;" } })
Upvotes: 1