How to get an array of elements of one model from the form asp.net core?
Solution 1:
1.If you just want to post single model, but the backend you want receive the IEnumerable<Check>
, you need add name attribute(name="[0].propertyName"
) to override the asp-for
generated name="check.propertyName"
2.For your code, it will generate multiple forms with submit button. If you want to post an array model, you need move <form>
and submit button outside foreach loop.
3.If post array model from view to controller. The IEnumerable<Check> Checks
is a list model, so the model binding system would find the name by [i].propertyName
.
4.<p>
element text cannot passed to backend by form submit. If you want to post it, try to add a hidden input.
If post array model from view to controller, change your view like below:
@model IEnumerable<Check>
@{
int i=0; //add this...
}
<form asp-action="Check" asp-controller="Home" method="post">
@foreach (var check in Model)
{
<p>
@check?.Text
<input type="text"asp-for="@check.Text" name="[@i].Text" hidden/> @* //add the hidden input*@
</p>
//add the name...
<p><input type="text"asp-for="@check.Number1" name="[@i].Number1"/></p>
@if(check.Number1 == check.Number2)
{<p>ok</p>}
i++; //add this...
}
<div class="form-group">
<input type="submit" value="Ok" class="btn btn-default" />
</div>
</form>
If you post single model, change your view like below:
@foreach (var check in Model)
{
<form asp-action="Check " asp-controller="Home" method="post">
<p>
@check?.Text
<input type="text"asp-for="@check.Text" name="[0].Text" hidden/> @* //add the hidden input*@
</p>
@*add the name...*@
<p><input type="text"asp-for="@check.Number1" name="[0].Number1"/></p>
@if(check.Number1 == check.Number2)
{<p>ok</p>}
<div class="form-group">
<input type="submit" value="Ok" class="btn btn-default" />
</div>
</form>
}