在 asp 辅助标签中,Model.PropertyName 和只是 PropertyName 有什么区别

In asp helper tags, what is the difference between Model.PropertyName and just PropertyName

这是一个例子:

cshtml >>

<label>List of products: </label>
<select asp-items="Model.ListOfProducts" asp-for="ProductToSearch">
    <option value="">All</option>
</select>

cshtml.cs >

public class IndexModel : PageModel
{
   ...

    public SelectList ListOfProducts{get; set;}

    [BindProperty(SupportsGet=true)]
    public string ProductToSearch{get; set;} 
   ...
}

在 cshtml 中,为什么一个名为 Model.ListOfProducts 而另一个名为 ProductToSearch。 在这种情况下,模型是做什么的?

您提供给 asp-items 的列表可能来自模型外部的某处,因此您必须指定完整的 namespace/class 对象路径(或生成对象的方法)想用

而在 asp-for 中,您应该始终指定当前模型的 属性,因此无需为其添加前缀。

它与标签助手上那些属性的实际类型有关。例如,asp-for 属性由标记助手 class 上的 属性 支持,类型为 ModelExpression。因此,您传递给视图中的属性的内容应该是可以解释为 ModelExpression 的内容,即模型上某个级别的特定 属性 的表示。在其他情况下,例如 asp-items,类型是 IEnumerable<SelectListItem>,因此您应该传递该类型的值。

简单地说,@Model.Property 的语法是一个取消引用:您正在检索 属性 的值,而当您只是执行 Property 时,您正在传递一个表达式表示 属性。

有一种情况会稍微模糊界限:当模型是一个列表并且您专门尝试将该列表中的特定项目引用为表达式时。在这种情况下,[0].Property 之类的表达式不是有效表达式,因此您必须使用 @Model[0].Property.