Reputation: 14511
I am trying to pass all data from an array inside my view back to a controller. I'm not sure how to do this using my ViewModel.
Model Class
public class ResultsViewModel
{
public int?[] ProgramIds { get; set; }
}
Form inside of the View
@using (Html.BeginForm("ExportCsv", "SurveyResponse", FormMethod.Post))
{
// Should I be looping through all values in the array here?
@Html.HiddenFor(x => x.ProgramIds)
<input type="submit" value="Submit" />
}
Controller I am posting to
[HttpPost]
public ActionResult ExportCsv(ResultsViewModel ResultsViewModel)
{
}
Upvotes: 2
Views: 5113
Reputation: 4072
Should I be looping through all values in the array here?
Yes, but don't use @Html.HiddenFor(..), since it seems to generate invalid HTML, because it generates controls with identical IDs:
<input id="ProgramIds" name="ProgramIds" type="hidden" value="3" />
<input id="ProgramIds" name="ProgramIds" type="hidden" value="4" />
Instead loop the list and create your own hidden html fields:
for (var i = 0; i < Model.ProgramIds.Length; i++)
{
<input type="hidden" name="ProgramIds[@i]" value="@Model.ProgramIds[i]" />
}
Scott Hanselman has written a blog post about this: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
Upvotes: 3
Reputation: 17288
Should I be looping through all values in the array here?
Yes, try this:
for (var i = 0; i < Model.ProgramIds.Length; i++)
{
@Html.HiddenFor(x => Model.ProgramIds[i])
}
Upvotes: 1