关于ASP.NET MVC:@ html.Label和@ html.LabelFor之间的区别

Difference between @html.Label and @html.LabelFor

本问题已经有最佳答案,请猛点这里访问。

@html.Label()@html.LabelFor()有什么区别?

另外,在Razor上下文中的强类型视图和非强类型视图的情况下,使用这些方法的语法是什么?


LabelFor将使用您在视图上设置的Model创建类型化的html帮助器。由于您在模型的属性上使用Attributes,例如Display(),因此它使代码的编写变得容易,并基于模型生成HTML。

1
2
3
4
5
6
// Model
public class YourModel
{
    [DisplayName("Some property")]
    public string YourProperty { get; set; }
}

并在视图中...

1
2
3
// View
@model YourModel
@Html.LabelFor(m => m.YourProperty)

Label仅用于在视图中生成标签,不必与Model关联。

1
2
// View
@Html.Label("YourProperty")

两者都将生成此HTML输出

1
<label for="YourProperty">YourProperty</label>

两者都会生成一个Label标签。

如果未使用模型键入View或PartialView,则不能使用LabelForEditorForTextBoxFor html帮助器,而不能使用LabelTextBox等。

如果在无类型的部分视图中添加Html.Label("field"),它将使用主视图的模型生成。每次您可以从View局部视图时,都会传递模型。如果模型为null,则仅呈现Label标记,如果模型具有此属性,则html helper将读取该值并将其呈现。

查看asp.net mvc的内部代码源中的Label扩展。