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 th
The foreach
loop instead of a for
loop might be a slightly cleaner solution.
@foreach(var item in Model.ToGroups)
{
@Html.HiddenFor(model => item)
}
You can take a look on this solution.
Put only HiddenFor inside the EditorTemplate.
And in your View put this: @Html.EditorFor(model => model.MyList)
It should works.
What about using Newtonsoft to deserialize the object into a json string and then insert that into your Hidden field e.g. (Model.DataResponse.Entity.Commission is a List of simple "CommissionRange" objects as you'll see in the JSON)
@using (Ajax.BeginForm("Settings", "AffiliateProgram", Model.DataResponse, new AjaxOptions { UpdateTargetId = "result" }))
{
string commissionJson = JsonConvert.SerializeObject(Model.DataResponse.Entity.Commission);
@Html.HiddenFor(data => data.DataResponse.Entity.Guid)
@Html.Hidden("DataResponse_Entity_Commission", commissionJson)
[Rest of my form]
}
Renders as:
<input id="DataResponse_Entity_Commission" name="DataResponse_Entity_Commission" type="hidden" value="[{"RangeStart":0,"RangeEnd":0,"CommissionPercent":2.00000},{"RangeStart":1,"RangeEnd":2,"CommissionPercent":3.00000},{"RangeStart":2,"RangeEnd":0,"CommissionPercent":2.00000},{"RangeStart":3,"RangeEnd":2,"CommissionPercent":1.00000},{"RangeStart":15,"RangeEnd":10,"CommissionPercent":5.00000}]">
In my case I do some JS stuff to edit the json in the hidden field before posting back
In my controller I then use Newtonsoft again to deserialize:
string jsonCommissionRange = Request.Form["DataResponse_Entity_Commission"];
List<CommissionRange> commissionRange = JsonConvert.DeserializeObject<List<CommissionRange>>(jsonCommissionRange);
It's a bit of a hack, but if @Html.EditorFor
or @Html.DisplayFor
work for your list, if you want to make sure it's sent on the post request but not visible, you could just style it to using display: none;
to hide it instead, e.g:
<div style="display: none;">@Html.EditorFor(model => model.MyList)</div>
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.
Html.HiddenFor
is designed for only one value. You will need to serialize your list in some way before creating the hidden field.
For example, if your list is of type string, you could join the list into a comma separated list, then split the list after post back in your controller.