ohyeah ohyeah - 1 year ago 84
ASP.NET (C#) Question

Store checkbox group in @Html.HiddenFor

In one view, I have a group of checkboxes that map to a



<input name="foo.IntegerList" type="checkbox" value="1">
<input name="foo.IntegerList" type="checkbox" value="2">
<input name="foo.IntegerList" type="checkbox" value="3">
<input name="foo.IntegerList" type="checkbox" value="4">
<input name="foo.IntegerList" type="checkbox" value="5">


<public ActionResult DoStuff(Foo foo)
//do stuff


public class Foo
IEnumerable<int> IntegerList

Submitting this form posts to the DoStuff action gives it a populated

Now, I have to use
in another view, and as a hidden field. In another view, I use this code:

@Html.HiddenFor(p => p.IntegerList)

But this gets translated to the following HTML:

<input name="IntegerList" type="hidden" value="">

Note that the value isn't set. How do I make
generate the correct hidden field?

Answer Source

You have to iterate over them an put the name with an index, something like this:

@for(int i = 0; i < Model.IntegerList.Count; i++)
    <input name="IntegerList[@i]" type="hidden" value="@Model.IntegerList[i]">

With HiddenFor it's done something like this

@for(int i = 0; i < Model.IntegerList.Count; i++)
    @Html.HiddenFor(model => Model.IntegerList[i])