How to change the display name for LabelFor in razor in mvc3?

前端 未结 5 1882
日久生厌
日久生厌 2021-01-30 15:22

In razor engine I have used LabelFor helper method to display the name

But the display name is seems to be not good to display. so i need to change my displ

5条回答
  •  有刺的猬
    2021-01-30 16:07

    This was an old question, but existing answers ignore the serious issue of throwing away any custom attributes when you regenerate the model. I am adding a more detailed answer to cover the current options available.

    You have 3 options:

    • Add a [DisplayName("Name goes here")] attribute to the data model class. The downside is that this is thrown away whenever you regenerate the data models.
    • Add a string parameter to your Html.LabelFor. e.g. @Html.LabelFor(model => model.SomekingStatus, "My New Label", new { @class = "control-label"}) Reference: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.labelextensions.labelfor(v=vs.118).aspx The downside to this is that you must repeat the label in every view.
    • Third option. Use a meta-data class attached to the data class (details follow).

    Option 3 - Add a Meta-Data Class:

    Microsoft allows for decorating properties on an Entity Framework class, without modifying the existing class! This by having meta-data classes that attach to your database classes (effectively a sideways extension of your EF class). This allow attributes to be added to the associated class and not to the class itself so the changes are not lost when you regenerate the data models.

    For example, if your data class is MyModel with a SomekingStatus property, you could do it like this:

    First declare a partial class of the same name (and using the same namespace), which allows you to add a class attribute without being overridden:

    [MetadataType(typeof(MyModelMetaData))]
    public partial class MyModel
    {
    }
    

    All generated data model classes are partial classes, which allow you to add extra properties and methods by simply creating more classes of the same name (this is very handy and I often use it e.g. to provide formatted string versions of other field types in the model).

    Step 2: add a metatadata class referenced by your new partial class:

    public class MyModelMetaData
    {
        // Apply DisplayNameAttribute (or any other attributes)
        [DisplayName("My New Label")]
        public string SomekingStatus;
    }
    

    Reference: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute(v=vs.110).aspx

    Notes:

    • From memory, if you start using a metadata class, it may ignore existing attributes on the actual class ([required] etc) so you may need to duplicate those in the Meta-data class.
    • This does not operate by magic and will not just work with any classes. The code that looks for UI decoration attributes is designed to look for a meta-data class first.

提交回复
热议问题