ASPNET中的绑定MVC CORE与@for一起使用但不与@foreach

时间:2017-10-26 16:05:37

标签: razor asp.net-core asp.net-core-mvc model-binding

如果我在页面中使用@foreach razor,有人知道为什么绑定系统无效吗?

...看

我创建了一个简单的MVC Asp.NET Core 2.0应用程序。它仅用于研究提议!

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视图 - 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>

要测试&#34;问题&#34;或我的错误,请在第一个和第二个循环之间反转注释。

如果我使用@for循环,绑定系统正确匹配BindController的类型,但是否则,使用@foreach,它不会发生。为什么????

0 个答案:

没有答案