【问题标题】:Handling collection in asp.net core using EditorFor使用 EditorFor 在 asp.net 核心中处理集合
【发布时间】:2018-01-09 21:41:24
【问题描述】:

在 ASP.NET Core 应用程序中,我有以下代码来处理字符串集合

  @for (int i = 0; i < Model.Detail.AccountNumbers.Count; i++)
  {
     <input asp-for="Detail.AccountNumbers[i]" class="form-control" />
  }

我想重构上面的代码以使用EditorFor。所以我创建了一个局部视图_AccountNumberEditor.cshtml 并把它放在EditorTemplates 中,然后重构代码如下。

  @for (int i = 0; i < Model.Detail.AccountNumbers.Count; i++)
  {
     @Html.EditorFor(x=>x.Detail.AccountNumbers[i],"_AccountNumberEditor")
  }

_AccountNumberEditor.cshtml

    @model string
    <input asp-for="?????" class="form-control" />

由于帐号只是string,我有string 类型的模型。 asp-for 属性的值是多少,以便创建正确的名称和 id 属性

【问题讨论】:

  • 不相关,但是EditorTemplates应该和类名一样命名(即AccountNumber.cshtml假设是类名),然后它只是@Html.EditorFor(m =&gt; m.Detail.AccountNumbers)(没有循环) .您可以随时使用@model string @Html.TextBoxFor(m =&gt; m, new { @class = "form-control" })

标签: asp.net-mvc asp.net-core asp.net-mvc-5 asp.net-core-mvc


【解决方案1】:

我找到了。当模型是字符串类型时,我只需要使用@Model

<input asp-for="@Model" class="form-control" />

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms#expression-names

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2021-12-18
    • 2017-10-12
    • 2020-01-28
    • 2021-06-25
    相关资源
    最近更新 更多