I need to store an array of string in a HiddenField in my webform with asp.net. Can anybody please tell me how I can achieve that? Thanks
Existing Answers
I'd always rather use the default property and model binder than having to wrap an array into a CSV and having to worry about splitting it and joining it on every single round trip to the client (as in the answers by @Mike Christensen and @codingbiz). This is exactly what the model binder is there for.
@David's answer points us in the right direction, but I'd rather not inline that type of logic into your view and relegate it to an EditorTemplate instead.
Preferred Solution
So you can add the following view ~/Views/Shared/EditorTemplates/HiddenArray.cshtml
@model Array
@foreach (var value in Model)
{
<input type="hidden" value="@value"
name="@Html.NameFor(model => model)"
id="@(Html.IdFor(model => model))_@value" />
}
Then call like this from your model:
<!-- language: lang-html -->@Html.EditorFor(model => model.FavoriteAnimals, "HiddenArray")
Alternative Strategies
Here's how I arrived at manually specifying the name and id variable for each hidden input:
- A) Can't use
HiddenFor()
inside a loop because it thinks the property name now includes the value - B) When we call EditorFor, the current model is added to the Route Prefix so if we pass the current model name as a string to to
Hidden()
we'll actually double up and the property name won't be able to bind on the way back. - C) It feels odd, but we can just pass an empty string as the name and rely on the Route Prefix to do its job, but because we're inside a loop, the ID that gets produced isn't valid HTML
- D) By grabbing the name and ID from the model and incrementing the dummy ID, we can continue to output valid HTML, even though it's probably not likely to affect anything but html linters and audits