user547794
user547794

Reputation: 14511

Post Array of values from View back to controller

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

Answers (2)

Henrik Stenb&#230;k
Henrik Stenb&#230;k

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

webdeveloper
webdeveloper

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

Related Questions