简体   繁体   中英

Using MVC4, is there a way I can add html classes to Html.TextBoxFor generated inputs in C#?

I want to place an attribute, say "[MyVmAttribute]", on a property in my viewmodel, and every HTML.TextBoxFor created on that property should have an html class added to reflect that fact, let's say "class-from-attribute" or something. My need is actually much more complex than this, but I need to know WHERE to force this "look for an attribute and add a class based on it" functionality.

Important note:

This has nothing to do with validation, so inheriting ValidationAttribute and hijacking the data-attribute rules functionality there seems wrong.

Why not just add the classes to your model and bind them to the Textbox?

@Html.TextBoxFor(m => m.UserName, new { @class = '@Model.MyStyle' })

You can also just set it directly if it doesn't have to be dynamic

 @Html.TextBoxFor(m => m.UserName, new { @class = "someClass" })

You could create your own editor Editor Template .

This would mean you would specify instead of TextBoxFor , you would go EditorFor , and call your custom template.

Then in the template, you would look for your custom attributes MyVmAttribute , get the name/value and inject it into either your own HTML textbox <input type='text' /> or TextBoxFor .

Example, in your view:

@Html.EditorFor(x=>x.MyProperty,"MyEditorTemplate")

In your editor template (located in ~/Views/Shared/EditorTemplates/MyEditorTemplate.cshthml):

@model String
//code to get custom attribute (HtmlKeyValueAttribute) out of `ViewData.ModelMetadata`
//and insert it as either
//@Html.TextBox
//OR
//<input type='text' />
//adding the attribute(s) in a foreach possibly

Your attribute I would suggest something that can be used multiple times:

public class HtmlKeyValueAttribute : Attribute
{
    public String Name {set;get;}
    public String Value {set;get;}

    public HtmlKeyValueAttribute(String name, String value)
    {
        this.Name = name;
        this.Value = value;
    }
}

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