0

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????

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Rafael
  • 966
  • 12
  • 22
  • 1
    Yes, this been like this since MVC 1. It's just a qwirk of the system. Basically it needs to know where it is in the array and can't with a foreach – Liam Oct 26 '17 at 16:10
  • @Liam is it related to the same issue of C# that allows us to change an item in 'for' statment, but not one in 'foreach'? – Rafael Oct 26 '17 at 16:21
  • [This answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) give a bit more explanation of how the `DefaultModelBinder` matches the `name` attributes of your form controls –  Oct 26 '17 at 21:00

0 Answers0