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