Search code examples
c#asp.netasp.net-mvc-3hidden-field

@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?


Solution

  • 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.