0

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!

blubberbo
  • 4,441
  • 4
  • 23
  • 36
  • Yes you can create your own `MyListBoxFor()` method(s) that calls the inbuilt `ListBoxFor()` method(s) and add additional values to the `htmlAttributes` parameter –  Jun 23 '16 at 23:56
  • I am not very comfortable with C# or mvc yet, would you possibly mind writing out a sample of what you mean exactly? – blubberbo Jun 23 '16 at 23:57
  • 2
    Its unclear why you would need to do this - why not just use `@Html.ListBoxFor(m => m.someProperty, Model.Options, new { data_someName = "someValue" })` –  Jun 24 '16 at 00:00
  • oh, does that work? haha i wouldnt use that because I didn't know that existed – blubberbo Jun 24 '16 at 00:00
  • Sure - that would generate ` –  Jun 24 '16 at 00:02

2 Answers2

0

Razor do the work for you:

@Html.AnythingHelperObject("NameOrId", new {data-yourcustomdatadom = "valueofdatadom"})
Paulo Rodrigues
  • 723
  • 1
  • 5
  • 16
  • well i more meant how to write the actual `AnythingHelperObject` to return back the write htmlstring :) but yeah, razor rocks – blubberbo Jun 24 '16 at 01:05
0

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.

Community
  • 1
  • 1