261

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?

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406
  • possible duplicate of [Hyphenated html attributes with asp.net mvc](http://stackoverflow.com/questions/2897733/hyphenated-html-attributes-with-asp-net-mvc) – ED-209 Jan 16 '14 at 08:47

1 Answers1

442

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") } 
    }
) %>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 8
    Is this behaviour specified anywhere :) ? – Rookian Jul 23 '12 at 13:37
  • @Rookian, I have no idea if it is specified anywhere. I guess some blog posts over the internet oughta be talking about it. – Darin Dimitrov Jul 25 '12 at 07:53
  • 5
    @Ryan, no it doesn't because it does't make sense to work for `EditorFor`. The EditorFor helper is used to render a custom HTML template that corresponds to the given type. A template could contain many elements, so talking about attributes in a template doesn't really make sense. Of course you could always write a custom template that works with the `additionalViewData` parameter that could be passed to an editor template and simply output them as attributes on the corresponding input field. – Darin Dimitrov Jul 29 '13 at 20:14
  • 2
    Just to be clear the resulting markup has an underscore and not hyphen. The sentence "You could use underscore (_) and the helper is intelligent enough to do the rest", specifically the bit about the supposed intelligence made me believe it would auto convert to - but it doesn't. HTML5 supports -. – Alan Macdonald Jul 02 '15 at 15:45
  • 2
    @AlanMacdonald the `_` is converted to `-` in older (middle?) versions of MVC. It may be that the most recent version(s) have dropped it, but I'm using it successfully on MVC 3 and 4. – brichins Oct 05 '15 at 19:32
  • 5
    @AlanMacdonald (and others reading), the `_` is converted to `-` in MVC 5, too. I'm using it successfully in a project I'm currently working on, which uses MVC 5. – Amy Barrett Jan 20 '17 at 09:53
  • It also appears to work with `EditorFor` in MVC 5, at least for a simple string property. – EarlCrapstone Jan 31 '17 at 14:58
  • How to show a text as a hyperlink in the TextBoxFor? Ex: If I copy-paste any url in this text box then it should show as a hyperlink to navigate that url by clicking. Is it possible in the text box? – Md Aslam Jan 27 '20 at 07:19