简体   繁体   English

使用MVC4,有没有一种方法可以将html类添加到Html.TextBoxFor C#中生成的输入?

[英]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. 我想在我的视图模型的一个属性上放置一个属性,例如“ [MyVmAttribute]”,并且在该属性上创建的每个HTML.TextBoxFor都应该添加一个html类来反映这一事实,比如说“ class-from-attribute”或者其他的东西。 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. 这与验证无关,因此继承ValidationAttribute并劫持数据属性规则功能似乎是错误的。

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 . 您可以创建自己的编辑器Editor Template

This would mean you would specify instead of TextBoxFor , you would go EditorFor , and call your custom template. 这意味着您将指定而不是TextBoxFor ,将进入EditorFor并调用自定义模板。

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 . 然后在模板中,您将查找自定义属性MyVmAttribute ,获取名称/值,并将其注入到您自己的HTML文本框<input type='text' />TextBoxFor

Example, in your view: 例如,您认为:

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

In your editor template (located in ~/Views/Shared/EditorTemplates/MyEditorTemplate.cshthml): 在您的编辑器模板中(位于〜/ 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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