mvc 自定义 html 助手可以继承基本助手吗?

can a mvc custom html helper inherit a base helper?

所以我希望能够在 razor 语法中向我的 @HTML.Listbox html 助手添加一个 data- 属性。我的理解是,如果不创建我自己的客户 html 助手,我就无法做到这一点。

我的问题是,有没有一种方法可以创建自定义 html 帮助器,但基本上继承基础 @HTML.Listbox 的所有内容,然后只需添加添加 data- 属性的功能?类似的东西是否已经存在?

提前致谢!

Razor 为您代劳:

@Html.AnythingHelperObject("NameOrId", new {data-yourcustomdatadom = "valueofdatadom"})

所有用于生成表单控件的内置 HtmlHelper 方法都有重载,允许您添加 html 属性。

对于ListBoxFor()方法,overloads are documented here。在你的情况下它

@Html.ListBoxFor(m => m.someProperty, Model.Options, new { data_someName = "someValue" })

这将生成

<select name="someProperty" id="someProperty" multiple="multiple" data-someName="someValue"> .... </select>

请注意,添加包含连字符的属性时,必须在方法中使用下划线(并且该方法会在呈现的 html 中将其转换为连字符)。

您还可以创建自己的 HtmlHelper 扩展方法,这些方法可以生成更复杂的 html 包括自动添加固定属性,例如,您可以创建一个 BootstrapTextBoxFor() 帮助程序来自动添加class="form-control" 属性

public static MvcHtmlString BootstrapTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, 
Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
    IDictionary<string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    attributes.Add("class", "form-control");
    ... other 'fixed' attributes as required
    return InputExtensions.TextBoxFor(helper, expression, attributes);
}

答案中显示了一些其他示例 here and