How can I bind an array with asp-for tag?
You need to use a valid expression with asp-for
that can be compiled, basically if index
is a variable you are using in a for loop then you would write <input asp-for="@Model.Requests[index].Name" />
Full example (I've used i
as the loop variable instead of index
):
@model MyProject.TodoItemList
<ul>
@for (int i = 0; i < Model.Requests.Count; i++)
{
<li>
<label asp-for="@Model.Requests[i].Name"></label>
<input asp-for="@Model.Requests[i].Name"/>
@* Or the old html helpers if you prefer
@Html.DisplayFor(model => model.Requests[i].Name)
*@
</li>
}
</ul>
For more info, check Expression names and Collections in the docs
If you want to bind the list using a separate partial view:
First, create your action that returns the list.
public async Task<ActionResult> UpdateTable([FromForm]Filter filter)
{
if (ModelState.IsValid)
{
List<Model> model = new List<Model>();
ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("Requests");
return PartialView("_PartialViewOfModel", model);
}
return BadRequest(ModelState);
}
And this code will go in your partial view.
@model List<Model>
@for (int i = 0; i < Model.Count; i++)
{
<input type="text" class="form-control form-control-sm" asp-for="@Model[i].Name" />
}