2

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)
        {

        }

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.