具有IEnumerable模型和输入标签帮助器的ASP.NET mvc视图 [英] ASP.NET mvc View with IEnumerable model and input tag helper
问题描述
在此官方ASP.NET Core教程,我可以使用输入代码帮助器,如下所示.但是由于 foreach循环中表单元素的已知模型绑定问题,我想改用for loop
. 问题:如果我要在以下View
中将@foreach (var item in Model)
替换为@for (int i=0; i < Model.Count(); i++)
. <input asp-for="???" />
中的asp-for
是什么?由于某种原因,智能感知无法识别,例如Model [i] .BlogId或@Model [i] .BlogId
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>
推荐答案
我遇到了同样的问题,并通过以下方式解决了该问题:
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"/>
}
重要的部分是使用for
循环,并通过@Model
访问asp-for
.
The important part is using the for
loop, and accessing the asp-for
via @Model
.
也就是说,如果您的模型本身应为IEnumerable
,则应重新考虑.而是为其创建一个属性.另外,您还需要确保可以通过索引访问您的收藏集.您可以将属性设置为IList
类型.为它分配IEnumerable
时,可以先调用ToList
.
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.
这篇关于具有IEnumerable模型和输入标签帮助器的ASP.NET mvc视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!