Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 260
nam Avatar asked Sep 11 '16 22:09

nam


1 Answers

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.

like image 199
Christian Gollhardt Avatar answered Sep 24 '22 11:09

Christian Gollhardt