What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

前端 未结 4 1092
离开以前
离开以前 2020-12-24 04:23

What\'s the difference between @Html.Label(), @Html.LabelFor() and @Html.LabelForModel() methods?

4条回答
  •  误落风尘
    2020-12-24 05:04

    Html.Label gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression):

    // Model
    public string Test { get; set; }
    
    // View
    @Html.Label("Test")
    
    // Output
    
    

    Html.LabelFor gives you a label for the property represented by the provided expression (typically a model property):

    // Model
    public class MyModel
    {
        [DisplayName("A property")]
        public string Test { get; set; }
    }
    
    // View
    @model MyModel
    @Html.LabelFor(m => m.Test)
    
    // Output
    
    

    Html.LabelForModel is a bit trickier. It returns a label whose for value is that of the parameter represented by the model object. This is useful, in particular, for custom editor templates. For example:

    // 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
    
    

提交回复
热议问题