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

Time:11-04

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 >
        @foreach(var rec in Model.Records)
        {
            <input type="hidden" name = "Records" value="@rec" asp-for="Records" />
        }
    <button type="button"  data-dismiss="modal">Close</button>
        <button type="submit"  id="confirm">Confirm</button>
    </div>
</form>

CodePudding user response:

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  type="submit">Save</button>   
    </div>
</form>
  • Related