Search code examples
.netasp.net-mvc-3webgrid

Add custom attributes to table rendered by WebGrid


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:

  1. WebGrid.GetHtml() calls System.Web.WebPages.Html.ObjectToDictionary to convert the anonymous attributes object to a dictionary. Unlike the method System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes used by other helpers, this doesn't replace "_" by "-".

  2. Unlike most other MVC helpers, WebGrid.GetHtml() does not have an overload that takes an IDictionary<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?


Solution

  • 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.