Search code examples
c#asp.net-mvcmodel-bindingmodelstate

MVC html.DropdownFor: binding the list and the selection


I'm using a model state check. So when there is an error I want to return the user the same model that was filled out. My form however has html.DropDownListFor.

 @Html.DropDownListFor(x => x.Item.SelectedId, Model.ItemList)

The drop down list will error saying that my select list (Model.ItemList) is null. This is because the dropDownListFor bound the selected value correctly but now the list is null on my post action. Is there a default way to solve this. With the list itself getting bound and the selected value.

I know I could do a html.HiddenFor and bind the whole list with like something like:

<input name="name[0].Id" type="text" />
<input name="name[1].Id" type="text" />
<input name="name[2].Id" type="text" />

Or I could even write my own extension to do this for me.

Right now on the post action I am just repopulating the select list, but I was curious is there was another way as my searches did not come up with anything.


Solution

  • It seems that there isn't any built in functionality that would help with model state and select list.

    As this link refers to that as much as well. http://benfoster.io/blog/automatic-modelstate-validation-in-aspnet-mvc