Search code examples
c#listrazorasp.net-core-mvc

List count is 0 when passing list to controller action action from view


I have this endpoint

[HttpPost]
public async Task<IActionResult> Save(myViewModel viewModel)
{
  ....
}

The view model I am passing in contains a list

public class MyViewModel
{
    public List<Records> Records {get;set;}
}

public class Record
{
    public Guid RecordId{ get; set; }
    public String Name{ get; set; }
}

When I pass it to my action via the cshtml form the count of the list appears as:

count = 0 

Despite knowing there is at least 1 record present and I am passing it in like this:

<form>
    <div class="modal-footer">
        @foreach(var rec in Model.Records)
        {
            <input type="hidden" name = "Records" value="@rec" asp-for="Records" />
        }
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary" id="confirm">Confirm</button>
    </div>
</form>

Solution

  • Use indexing for the list elements to prepare the context for the binding to work properly:

    @model MyViewModel
    <form asp-action="Save" method="post">
        <div>
            @for(int i=0; i < Model.Records.Count; i++)
            {
                <input type="hidden" asp-for="@Model.Records[i].Name" />
                <input type="hidden" asp-for="@Model.Records[i].RecordId" />
            }     
            <button class="button" type="submit">Save</button>   
        </div>
    </form>