Someone knows why the binding system is not working if I use @foreach razor in a page?
Look...
I've created a simple MVC Asp.NET Core 2.0 App. Its just for study propose!
1 Controller - BindController.cs
public class BindController : Controller
{
public static List<Bind> lista = new List<Bind>()
{
new Bind(){Id=1, Nome="Rafael"},
new Bind(){Id=2, Nome="Dhiego"},
new Bind(){Id=3, Nome="Rodrigo"},
new Bind(){Id=4, Nome="Kleber"}
};
// GET: /<controller>/
public IActionResult Index()
{
return View(lista);
}
[HttpPost]
public IActionResult Index(List<Bind> listas)
{
return View(lista);
}
}
1 View - Index.cshtml
@model List<Bind>
<form asp-action="Index" method="post">
@*Binding works here*@
@*@for (int i = 0; i < Model.Count; i++)
{
<div>
<label asp-for="@Model[i].Nome"></label>
<input asp-for="@Model[i].Nome" />
</div>
}*@
@*But doesn't here*@
@foreach (var item in Model)
{
<div>
<label asp-for="@item.Nome"></label>
<input asp-for="@item.Nome"/>
</div>
}
<input type="submit" class="btn btn-default" value="Update" />
</form>
To test the "problem", or my mistake, invert the comment between first and second loop.
If I use the @for loop the bind system correct match the type to the BindController, but otherwise, using @foreach, it not occurs. Why????