对列表项使用tag-helper验证

时间:2017-08-01 13:55:08

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

我见过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循环 - 我该如何使其有效?

1 个答案:

答案 0 :(得分:2)

来自docs

  

asp-for属性值是ModelExpression,是lambda表达式的右侧。因此,asp-for="Property1"在生成的代码中变为m => m.Property1,这就是您不需要使用Model作为前缀的原因。您可以使用&#34; @&#34;用于启动内联表达式并在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 -->
}