asp.net-mvcpostrazorasp.net-core-mvcform-submit

How to pass to a POST controller action method the model, including the contents of a List object member property?


I have a Razor page in which a controller GET action method returns the model to the view. That model contains a member which is a

List<int> ids

Now I want to call a POST method on the controller when I submit that page, passing the model, but it is not passing the contents of that List<int> ids member, as I always get an empty List.

I have even put hidden fields like this on the view, inside the form:

@foreach (var id in model.ids)
{
    @Html.HiddenFor(model => model.ids, new{ @name= "ids", @value = id})
}

Now I get an null List instead.

Where is the problem?


Solution

  • Your code will generate value="System.Collections.Generic.List`1[System.Int32]"

    <input data-val="true" data-val-required="The ids field is required." id="ids" name="ids" type="hidden" value="System.Collections.Generic.List`1[System.Int32]" />
    

    Html.HiddenFor returns an HTML hidden input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. Html.HiddenFor is designed for only one value. Th follow options make model binding work correctly and pick up all of your hidden values in the list.

    Try the code like :

    Option 1:

     @foreach (var id in Model.ids)
     {      
           <input name="ids" type="hidden" value="@id" />
     }
    

    Option 2:

      @for (int i = 0; i < Model.ids.Count; i++)
      {
          @Html.HiddenFor(model => Model.ids[i])
      } 
    

    result:

    enter image description here