如何创建像Html.TextBox这样的方法,为渲染的文本框添加属性?

时间:2013-07-20 23:47:55

标签: asp.net-mvc html-helper

我熟悉使用Html.TextBox方法渲染文本框。假设我想编写一个类似于Html.TextBox的方法,但是需要一个名为Abc的附加字符串属性,它将TextBox呈现为与TextBox呈现的类似,但添加了一个名为{{1的属性使用data-abc指定的值。

这样做的好方法是什么?

2 个答案:

答案 0 :(得分:2)

将属性data_abc添加到可选参数中,并将其添加为data-abc。

@Html.TextBox("Name", "Default Value", new { data_abc = "data" });
祝你好运!

答案 1 :(得分:0)

这是我提出的似乎有效的方法:

    public static MvcHtmlString MyTextBox<T>(this HtmlHelper helper, string name, string value, object htmlAttributes, string Abc)
    {
        IDictionary<string, object> myHtmlAttributes = new RouteValueDictionary(htmlAttributes);

        myHtmlAttributes.Add("data-abc", Abc);

        return helper.TextBox(propertyName, value, myHtmlAttributes);
    }