开发者

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?


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.


Consider what ASP.NET MVC is designed to do. It is designed to give you tight control over the HTML that you produce. If something is not accessible, you won't have to jump through hoops to fix it. What you are trying to do is create invalid HTML, or XHTML. Instead of trying to make HTML that is invalid simplify to just using an ID. #1 on the accessibility guidelines is that the HTML is valid for the declared type.

As long as the ID is unique within the document you will have satisfied HTML conformance--and it will make it much easier to manipulate with jQuery.

If I may, why are you trying to create invalid HTML? Or is this a proprietary XML format?

BTW, MVC 3 RC came out today.


Edit:

Playing with HTML5 features, while "shiny" and kool, are unstable. Many parts of the specification are changing as often as weekly. What is considered good now may not be good when the final spec is released. MVC 3 does have some things that will make your job more friendly, for now you have to use a dictionary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜