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?
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 :-)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With