【问题标题】:Mvc Core: Validation attributes are generated once for dublicated namesMvc Core:为重名生成一次验证属性
【发布时间】:2020-05-09 21:39:39
【问题描述】:

这是一个类似于old one 的问题,但在旧问题中,其原因被标记为答案。

我的页面,有一个包含多个项目的表单。每个项目都包含一些元素,因此它们的名称是重复的。

<form ...>
    .....
    <table class="details">
        <thead>
            <tr>
                <th>Prop1</th>
                <th>Prop2</th>
            </tr>
        </thead>
        <tbody>
            @foreach(var item in Model.Items)
            {
               @await Html.PartialAsync("partial-view-name", detail)
            }
        </tbody>
    </table>
    ...
</form>

部分

....
<tr>
   <td><input asp-for="Prop1" /></td>
   <td><input asp-for="Prop2" /></td>
</tr>

here 所述,这是设计的行为,但我想知道是否有任何方法可以覆盖它。

【问题讨论】:

    标签: validation asp.net-core asp.net-core-mvc unobtrusive-validation tag-helpers


    【解决方案1】:

    我找到了一种解决方案,可以在 HTML 字段中添加前缀,这样名称在迭代中会有所不同。

    @{ ViewData.TemplateInfo.HtmlFieldPrefix = Model.ID; }
    <tr>
       <td><input asp-for="Prop1"/></td>
       <td><input asp-for="Prop2"/></td>
    </tr>
    

    【讨论】:

      【解决方案2】:

      我认为您的问题是如何将每个对象渲染到屏幕上。如果您应用下面的逻辑,它应该会正确呈现并在提交时正确绑定回列表。

      @for (int i=0; i< Model.Items.Count; i++)
      {
          <div class="text-center">
             <label asp-for="@Model.Items[i].Prop1"></label>
             <input asp-for="@Model.Items[i].Prop1" />
             <label asp-for="@Model.Items[i].Prop2"></label>
             <input asp-for="@Model.Items[i].Prop2" />
          </div>
      }
      

      【讨论】:

      • 谢谢@eVolve,你说得对。我试图简化场景。这些项目处于局部视图中。请检查更新后的问题。
      • 好的,那你为什么不把你的列表传递到部分,然后在部分而不是你的主页中执行我上面建议的循环
      • 我使用了一个框架来生成视图和控制器,这个工具可能会生成 div 而不是表格,并将部分视图用于不同的目的。
      猜你喜欢
      • 1970-01-01
      • 2011-10-03
      • 2020-01-11
      • 1970-01-01
      • 2020-11-15
      • 2011-10-11
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多