问题
I am using an MVC3 WebGrid, and want to add custom attributes of the form "data-xxx" to the <table>
element rendered by WebGrid.GetHtml()
.
I tried to do this as follows:
grid.GetHtml(...
htmlAttributes: new { data_xxx = "value" }
);
However this renders as:
<table ... data_xxx="value">
instead of the expected:
<table ... data-xxx="value">
I.e. unlike other MVC helpers, it doesn't replace the underscore in the property name with a hyphen.
After a bit of spelunking with Reflector it seems that:
WebGrid.GetHtml()
callsSystem.Web.WebPages.Html.ObjectToDictionary
to convert the anonymous attributes object to a dictionary. Unlike the methodSystem.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes
used by other helpers, this doesn't replace "_" by "-".Unlike most other MVC helpers,
WebGrid.GetHtml()
does not have an overload that takes anIDictionary<string, object>
, so I can't work around the bug by specifying the attributes in this way.
This looks like a bug to me, and I've submitted it to Connect:
http://connect.microsoft.com/VisualStudio/feedback/details/767456/webgrid-gethtml-helper-does-not-allow-data-attributes-to-be-set
Any suggestions for a workaround? Or is it fixed in MVC4?
回答1:
Thanks for reporting this issue:
This was fixed yesterday in CodePlex by resolving issues 610 & 575.
https://aspnetwebstack.codeplex.com/workitem/610
https://aspnetwebstack.codeplex.com/workitem/575
You can try out the nightly bits.
来源:https://stackoverflow.com/questions/12900138/add-custom-attributes-to-table-rendered-by-webgrid