Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC2 Not replacing underscores with dashes in HtmlAttributes

I've heard from a couple of different sources that when using HTML helpers in ASP.NET MVC2, one can create custom attributes with dashes in them (e.g. <a data-rowId="5">) by using an underscore in place of the dash, and when the HTML is written to the page the underscores will be replaced by dashes.

So, something like this:

<%= HtmlActionLink(Model.Name, "MyView", null, new {data_rowId = Model.id}) %>

should render as

<a data-rowId="0" href="myURL">Row Name</a>

But... it's not. I think that maybe this feature is only enabled in the MVC3 Beta preview (as it's mentioned in the MVC3 preview release notes), but this thread is about the same thing, and it's regarding MVC2.

I know I can use the other solution presented in that thread, but I'd rather not have to resort to using the dictionary if a more elegant solution exists.

Anyone know if there's something simple I can do to get this particular thing working?

like image 743
Isochronous Avatar asked Feb 25 '23 21:02

Isochronous


2 Answers

Not exactly the most elegant solution but probably acceptable:

<%= Html.ActionLink(
    Model.Name, 
    "MyView", 
    null, 
    new Dictionary<string, string> { { "data-rowId",  Model.id } }
) %>

On a side note: data-rowId is a totally invalid attribute in HTML according to standard doctypes so maybe the most elegant solution would be to get rid of it :-)

like image 141
Darin Dimitrov Avatar answered Apr 07 '23 19:04

Darin Dimitrov


System.Web.Mvc.HtmlHelper provides a static method that does what you're looking for:

<%= Html.ActionLink(
    Model.Name, 
    "MyView", 
    null, 
    HtmlHelper.AnonymousObjectToHtmlAttributes(new { data_row_id: Model.id })
) %>

This method will will substitute underscores with hyphens - as somebody pointed out though, be sure to use all-lowercase attribute names, which are HTML5-compliant.

like image 35
mindplay.dk Avatar answered Apr 07 '23 20:04

mindplay.dk