So I want to be able to add a data-
attribute to my @HTML.Listbox
html helper in the razor syntax. My understanding is that I can't do this without creating my own customer html helper.
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? Does something like already exist?
Thanks in advance!
All the in-built HtmlHelper
methods for generating form controls have overloads the allow you to add html attributes.
For the ListBoxFor()
method, the overloads are documented here. 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).
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
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.