简体   繁体   中英

Assign arbitrary attribute to MVC model's property

In my MVC web application I have the bellow class:

public class LoginVM
{
    [Required]
    public string Username { get; set; }

    [Required]
    public string password { get; set; }
    public bool RememberMe { get; set; }
}

And in cshtml file I use EditorForModel to generate the form:

.cshtml

@Html.EditorForModel()

Now I want to know that is there any way to add some arbitrary attributes(for example css class attribute) to the html tag that is generating automatically?

Something like this:

    ...
    [Required]
    // Some code like this: [addAttribute("class", "myCssClass")] 
    public string Username { get; set; }
    ...

Agree with Comments by CodeCaster and Thorarins. It's not a good idea to mix up your Model with View related Attributes. In addition to using EditorTemplates/DisplayTemplates, you could also use the UIHintAttribute . It can help you to switch between different formats or also stylings within the View.

Some example:
http://www.shawnrenner.com/asp-net-mvc-custom-property-display-using-uihint/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM