ohyeah ohyeah - 3 months ago 24
ASP.NET (C#) Question

Store checkbox group in @Html.HiddenFor

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

List<int>
.

View:

<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">


Action:

[HttpPost]
<public ActionResult DoStuff(Foo foo)
//do stuff


Model:

public class Foo
{
IEnumerable<int> IntegerList
}


Submitting this form posts to the DoStuff action gives it a populated
List<int>
.

Now, I have to use
IntegerList
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
Html.HiddenFor
generate the correct hidden field?

Answer

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])
}