[英]can a mvc custom html helper inherit a base helper?
So I want to be able to add a data-
attribute to my @HTML.Listbox
html helper in the razor syntax. 因此,我希望能够以razor语法向我的@HTML.Listbox
html帮助器添加data-
属性。 My understanding is that I can't do this without creating my own customer html helper. 我的理解是,如果没有创建自己的客户html帮助器,我将无法做到这一点。
My question is, is there a way to create a custom html helper but basically inherit everything from the base @HTML.Listbox
and then just add the ability to add a data-
attribute? 我的问题是,有没有一种创建自定义html帮助器的方法,但是基本上是从基础@HTML.Listbox
继承所有内容,然后添加添加data-
属性的功能? Does something like already exist? 是否已经存在?
Thanks in advance! 提前致谢!
剃刀为您做的工作:
@Html.AnythingHelperObject("NameOrId", new {data-yourcustomdatadom = "valueofdatadom"})
All the in-built HtmlHelper
methods for generating form controls have overloads the allow you to add html attributes. 所有用于生成表单控件的内置HtmlHelper
方法都具有重载功能,允许您添加html属性。
For the ListBoxFor()
method, the overloads are documented here . 对于ListBoxFor()
方法, 此处记录了重载 。 In your case its 在你的情况下
@Html.ListBoxFor(m => m.someProperty, Model.Options, new { data_someName = "someValue" })
which will generate 会产生
<select name="someProperty" id="someProperty" multiple="multiple" data-someName="someValue"> .... </select>
Note when adding attributes containing a hyphen, you must use an underscore in the method (and the method will convert it to a hyphen in the rendered html). 请注意,在添加包含连字符的属性时,必须在方法中使用下划线(该方法会将其转换为呈现的html中的连字符)。
You can also create your own HtmlHelper
extension methods that can generate more complex html including automatically adding fixed attributes, for example you might create a BootstrapTextBoxFor()
helper that automatically adds a class="form-control"
attribute 您还可以创建自己的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);
}
Some other example are shown in the the answers here and here . 此处和此处的答案中还显示了其他一些示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.