What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel
1 2 3 4 5 6 7 8 | // Model public string Test { get; set; } // View @Html.Label("Test") // Output <label for="Test">Test</label> |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Model public class MyModel { [DisplayName("A property")] public string Test { get; set; } } // View @model MyModel @Html.LabelFor(m => m.Test) // Output <label for="Test">A property</label> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Model public class MyModel { [DisplayName("A property")] public string Test { get; set; } } // Main view @Html.EditorFor(m => m.Test) // Inside editor template @Html.LabelForModel() // Output <label for="Test">A property</label> |
1 2 3 4 5 | public class MyModel { [Display(Name="My property title") public class MyProperty{get;set;} } |
您认为:
1 | Html.LabelFor(x => x.MyProperty) //Outputs My property title |
在上面,LabelFor将显示
我认为
LabelForModel方法返回HTML标签元素和该模型表示的属性的属性名称。
您可以参考以下代码:
模型中的代码:
1 2 3 4 5 6 7 8 | using System.ComponentModel; [DisplayName("MyModel")] public class MyModel { [DisplayName("A property")] public string Test { get; set; } } |
查看代码:
1 2 3 4 5 6 7 8 | @Html.LabelForModel() @Html.LabelFor(model => model.Test, new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Test) @Html.ValidationMessageFor(model => model.Test) |
输出截图:
在asp.net论坛上参考答案
假设您需要一个带有文字customername的标签,而不可以使用2种方法来实现
1 2 3 | [1]@Html.Label("CustomerName") [2]@Html.LabelFor(a => a.CustomerName) //strongly typed |
第二种方法使用了模型中的属性。如果您的视图实现了模型,则可以使用第二种方法。
更多信息,请访问下面的链接
http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strong-typed-html-helpers.aspx