Html5 data-* with asp.net mvc TextboxFor html attributes

asp.net MvcHtmlasp.net Mvc-3

asp.net Mvc Problem Overview


How do I add data-* html attributes using TextboxFor?

This is what I currently have:

@Html.TextBoxFor(model => model.Country.CountryName, new { data-url= Url.Action("CountryContains", "Geo") })

As you see, the - is causing a problem here data-url. Whats the way around this?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

You could use underscore (_) and the helper is intelligent enough to do the rest:

@Html.TextBoxFor(
    model => model.Country.CountryName, 
    new { data_url = Url.Action("CountryContains", "Geo") }
)

And for those who want to achieve the same in pre ASP.NET MVC 3 versions they could:

<%= Html.TextBoxFor(
    model => model.Country.CountryName, 
    new Dictionary<string, object> { 
        { "data-url", Url.Action("CountryContains", "Geo") } 
    }
) %>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShawn McleanView Question on Stackoverflow
Solution 1 - asp.net MvcDarin DimitrovView Answer on Stackoverflow