【问题标题】:Using tag-helper validation for list items对列表项使用标签助手验证
【发布时间】:2017-08-01 13:55:08
【问题描述】:

我见过this question,它似乎完全涵盖了我想要做的事情,但由于某种原因,那里提供的解决方案对我不起作用。

我的看法如下:

@model ExerciseEditModel

@foreach (var item in Model.Rounds)
{
    <!-- bootstrap grid markup omitted -->
    <div class="form-group col-sm-3">
        <label asp-for="item.DurationEstimate"></label>
        <input asp-for="item.DurationEstimate" type="time" class="form-control" />
    </div>
    <!-- bootstrap grid markup, and more form elements, omitted -->
}

据我所知,这与链接问题中的解决方案的工作原理完全一致,但我在视图上遇到了构建错误,因为

“ExerciseEditModel”不包含“item”的定义,并且找不到接受“ExerciseEditModel”类型的第一个参数的扩展方法“item”(您是否缺少 using 指令或程序集引用?)

似乎asp-for 助手的范围没有注意到foreach 循环 - 我怎样才能让它工作?

【问题讨论】:

  • 奥卡姆剃刀问题:您是否在任何地方遗漏了using 声明?
  • @krillgar 也许,但在那种情况下,我不知道我缺少哪个using 语句(或者我需要哪个语句)。我应该寻找什么?
  • 我没有做过Core MVC,这就是我提出问题的原因。抱歉,我无法提供更多帮助,但看起来 David G 可以满足您的需求。
  • 您缺少前导@ - 即asp-for="@item.DurationEstimate",但是当您提交时这不会绑定到您的模型,您需要使用for 循环和asp-for=Model[i].DurationEstimate" - 参考@987654322 @) 更多解释

标签: c# asp.net-mvc razor asp.net-core


【解决方案1】:

来自docs

asp-for 属性值是 ModelExpression 和 lambda 表达式的右侧。因此,asp-for="Property1" 在生成的代码中变为m =&gt; m.Property1,这就是为什么您不需要前缀Model。您可以使用“@”字符开始内联表达式并移动到m.之前

所以你应该在你的表达式前加上@:

@model ExerciseEditModel

@foreach (var item in Model.Rounds)
{
    <!-- bootstrap grid markup omitted -->
    <div class="form-group col-sm-3">
        <label asp-for="@item.DurationEstimate"></label>
        <input asp-for="@item.DurationEstimate" type="time" class="form-control" />
    </div>
    <!-- bootstrap grid markup, and more form elements, omitted -->
}

【讨论】:

    猜你喜欢
    • 2019-11-07
    • 2016-12-09
    • 1970-01-01
    • 2017-05-10
    • 2012-04-30
    • 1970-01-01
    • 2019-06-16
    • 2011-04-22
    • 1970-01-01
    相关资源
    最近更新 更多