I'm using a model that contains a List as a property. I'm populating this list with items i grab from SQL Server. I want the List to be hidden in the view and passed to the POST action. Later on i may want to add more items to this List with jQuery which makes an array unsuitable for expansion later on. Normally you would use
@Html.HiddenFor(model => model.MyList)
to accomplish this functionality, but for some reason the List in POST is always null.
Very simple question, anyone know why MVC behaves like this?
You can take a look on this solution.
Put only HiddenFor inside the EditorTemplate.
And in your View put this:
@Html.EditorFor(model => model.MyList)
It should works.
maybe late, but i created extension method for hidden fields from collection (with simple data type items):
So here it is:
Usage is as simple as:
Another possible way to fix this would be to give each object in your List an ID, then use
@Html.DropDownListFor(model => model.IDs)
and populate an array which holds the IDs.Another option would be:
Html.HiddenFor
is designed for only one value. You will need to serialize your list in some way before creating the hidden field.For example, if your list is of type string, you could join the list into a comma separated list, then split the list after post back in your controller.
I started digging through the source code for
HiddenFor
, and I think the roadblock you're seeing is that your complex objectMyList
is not implicitly convertible to typestring
, so the framework treats yourModel
value asnull
and renders thevalue
attribute empty.