Add custom attributes to table rendered by WebGrid

时光怂恿深爱的人放手 提交于 2019-12-02 11:56:29

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!