razor - 带有 IEnumerable 模型和输入标签助手的 ASP.NET mvc View

标签 razor asp.net-core asp.net-core-mvc tag-helpers

在这个 official ASP.NET Core tutorial , 我可以使用 Input Tag Helper如下所示。但由于 known model binding issue of form elements in a foreach loop , 我想用 for loop反而。 问题 : 如果我要替换 @foreach (var item in Model)@for (int i=0; i < Model.Count(); i++)在下面View .我的 asp-for 会是什么?在 <input asp-for="???" /> ?由于某种原因,智能感知无法识别,例如 Model[i].BlogId 或 @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>

最佳答案

我遇到了同样的问题并以这种方式解决了它:

@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循环,并访问 asp-for通过 @Model .

也就是说,您应该重新考虑,如果您的模型本身应该是 IEnumerable .而是为它创建一个属性。您还需要确保您的收藏可以通过索引访问。你可以将你的属性设为 IList .当您分配 IEnumerable可以调用ToList前。

关于razor - 带有 IEnumerable 模型和输入标签助手的 ASP.NET mvc View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39441339/

相关文章:

c# - 在 asp.net 发布后为空?编辑模型

c# - 如何使用 Razor/C# 值预填充 'date' 输入字段

asp.net-mvc - 带有 UIHint 的 ASP.NET MVC 3 自定义显示模板 - 需要 For 循环吗?

c# - ValueTuple 在带有 MVC 5 的 Razor View 中不起作用

asp.net-mvc-3 - ASP.NET MVC View 模型未绑定(bind)到带有 DropDownList 的 HTTP Post

c# - 在 mac 中没有找到匹配命令 "dotnet-aspnet-codegenerator"asp.net core 2.1 项目的可执行文件

c# - 使用 ASP.Net 5 进行 JwtBearer 身份验证

javascript - Razor 中传递给 JavaScript 的变量内的转义 '@' 字符

c# - 在我的 Web api 端点中解析 HTTP POST 请求正文时出错

asp.net - 是否有 UI 来管理与 ASP.NET 5 兼容的 ASP.NET Identity 用户/角色?