使用 MVC4,有没有办法将 html 类添加到 Html.TextBox 用于在 C# 中生成的输入

本文关键字:用于 TextBox 输入 Html 有没有 MVC4 添加 html 使用 | 更新日期: 2023-09-27 18:37:24

我想在我的视图模型和每个HTML的属性上放置一个属性,比如"[MyVmAttribute]"。TextBox对于在该属性上创建的应该添加一个 html 类来反映这一事实,比如说"class-from-attribute"或其他东西。 我的需求实际上比这复杂得多,但我需要知道在哪里强制使用这种"查找属性并基于它添加类"功能。

重要提示:

这与验证无关,因此继承 ValidationAttribute 并劫持数据属性规则功能似乎是错误的。

使用 MVC4,有没有办法将 html 类添加到 Html.TextBox 用于在 C# 中生成的输入

为什么不直接将类添加到模型中并将它们绑定到文本框中?

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

如果它不必是动态的,您也可以直接设置它

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

您可以创建自己的编辑器编辑器模板。

这意味着您将指定而不是TextBoxFor,您将转到EditorFor,并调用您的自定义模板。

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

示例,在您看来:

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

在您的编辑器模板中(位于 ~/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

您的属性我会建议可以多次使用的东西:

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;
    }
}