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?
Faced the same issue. Without for loop, it only posted the first element of the list. After iterating through for loop, it can keep full list and post successfully.
I've just come across this issue and solved it simply by doing the following:
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.
It's a bit of a hack, but if
@Html.EditorFor
or@Html.DisplayFor
work for your list, if you want to make sure it's sent on the post request but not visible, you could just style it to usingdisplay: none;
to hide it instead, e.g: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.
What about using Newtonsoft to deserialize the object into a json string and then insert that into your Hidden field e.g. (Model.DataResponse.Entity.Commission is a List of simple "CommissionRange" objects as you'll see in the JSON)
Renders as:
In my case I do some JS stuff to edit the json in the hidden field before posting back
In my controller I then use Newtonsoft again to deserialize:
I've just found out (after a couple of hours of trying to figure out why model values weren't going back to the controller) that hidden for should follow the EditorFor.
Unless I am doing something else wrong this is what I found. I will not make the mistake again.
In the context of a Model that contains a list of another class.
This will NOT work:
Where as this WILL......