Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Html.HiddenFor does not work on Lists in ASP.NET MVC

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?

like image 454
Anton Smith Avatar asked Feb 21 '12 21:02

Anton Smith


People also ask

What is HTML HiddenFor in MVC?

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.

Can we store list in hidden field?

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.

How does HTML HiddenFor work?

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.


2 Answers

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.

like image 131
Daniel Mackay Avatar answered Oct 22 '22 01:10

Daniel Mackay


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.

like image 31
Erik Funkenbusch Avatar answered Oct 21 '22 23:10

Erik Funkenbusch