ASP.NET mvc View with IEnumerable model and input tag helper

妖精的绣舞 提交于 2019-12-07 03:19:40

问题


In this official ASP.NET Core tutorial, I can use an Input Tag Helper as shown below. But due to a known model binding issue of form elements in a foreach loop, I want to use for loop instead. Question: If I were to replace @foreach (var item in Model) with @for (int i=0; i < Model.Count(); i++) in the following View. What would be my asp-for in <input asp-for="???" /> ? For some reason, intellisense is not recognizing, e.g, Model[i].BlogId or @Model[i].BlogId

@model IEnumerable<EFGetStarted.AspNetCore.NewDb.Models.Blog>

@{
    ViewBag.Title = "Blogs";
}

<h2>Blogs</h2>

<p>
    <a asp-controller="Blogs" asp-action="Create">Create New</a>
</p>

<table class="table">
    <tr>
        <th>Id</th>
        <th>Url</th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                <input asp-for="@item.BlogId" />
            </td>
            <td>
                <input asp-for="@item.Url" />
            </td>
        </tr>
    }
</table>

回答1:


    @model IEnumerable<EFGetStarted.AspNetCore.NewDb.Models.Blog>

    @{
        ViewBag.Title = "Blogs";
    }

    <h2>Blogs</h2>

    <p>
        <a asp-controller="Blogs" asp-action="Create">Create New</a>
    </p>

    <table class="table">
        <tr>
            <th>Id</th>
            <th>Url</th>
        </tr>
    @for (int item = 0; item < Model.Count(); item++)
        {
           <tr>
              <td>
                <input name="@Model.ToList()[item].BlogId" />
              </td>
              <td>
                <input name="@Model.ToList()[item].Url" />
              </td>
          </tr>
       }
    </table>



回答2:


I had the same problem and solved it this way:

@for (int i = 0; i < Model.Translations.Count; i++)
{
    @Html.HiddenFor(m => m.Translations[i].LanguageId)
    <form-group-text asp-for="@Model.Translations[i].Content"/>
}

The important part is using the for loop, and accessing the asp-for via @Model.

That said, you should rethink, if your Model itself should be IEnumerable. Instead create a property for it. Also you need to make sure, your Collection is accessable via Index. You could make your property of type IList. When you assign an IEnumerable to it, you can call ToList before.



来源:https://stackoverflow.com/questions/39441339/asp-net-mvc-view-with-ienumerable-model-and-input-tag-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!