簡體   English   中英

使用MVC4,有沒有一種方法可以將html類添加到Html.TextBoxFor C#中生成的輸入?

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

我想在我的視圖模型的一個屬性上放置一個屬性,例如“ [MyVmAttribute]”,並且在該屬性上創建的每個HTML.TextBoxFor都應該添加一個html類來反映這一事實,比如說“ class-from-attribute”或者其他的東西。 我的需求實際上比這復雜得多,但是我需要知道在哪里強制執行“查找屬性並基於該屬性添加類”功能。

重要的提示:

這與驗證無關,因此繼承ValidationAttribute並劫持數據屬性規則功能似乎是錯誤的。

為什么不將類添加到模型並將它們綁定到文本框呢?

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

如果不必動態設置,也可以直接設置它

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

您可以創建自己的編輯器Editor Template

這意味着您將指定而不是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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM