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?
The Html. HiddenFor<TModel, TProperty> extension method is a strongly typed extension method generates a hidden input element for the model property specified using a lambda expression. Visit docs.microsoft.com to know all the overloads of HiddenFor() method. Example: HiddenFor() in Razor View.
Since the HiddenField can only hold string data which is the different type from Array. To store the Array, we need to Serialize the Array to string.
It creates a hidden input on the form for the field (from your model) that you pass it. It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.
I've just come across this issue and solved it simply by doing the following:
@for(int i = 0; i < Model.ToGroups.Count; i++) { @Html.HiddenFor(model => Model.ToGroups[i]) }
By using a for
instead of a foreach
the model binding will work correctly and pick up all of your hidden values in the list. Seems like the simplest way to solve this problem.
HiddenFor is not like a DisplayFor or EditorFor. It won't work with collections, only single values.
You can use the Serialize HTML helper available in the MVC Futures project to serialize an object to a Hidden field, or you will have to write the code yourself. A better solution is to simply serialize an ID of some sort and re-get the data from the database on postback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With