ASP MVC 3 - How to intercept all actions rendering to add conditionally html "class"?
I would like to know how is the best way to intercept all action being rendered to insert a conditiona开发者_如何学JAVAl html class.
I have a lot of situation when it will be useful, but think about an access control system where some actions cannot be accessed by current user, and would be nice to change or add a class to all urls rendered that matches this denied actions, disabling them or using any kind of visual effects to tell to the user that these links cannot be accessed (of course that, we are only talking about the visual indicators, because these actions will return permission denied if really accessed).
I think that one way would make a html helper that should be used by all programmers, so this helper would render the "class id" conditionally matching each action rendered to the actions permitted to the current user. But on this approach we need to entrust on all programmers to use this html helper instead of the others helpers.
Well, does somebody have any others suggestions to do that ? Would be nice if we could do that without depending of all programmers practices to use a specific html helper when coding Views.
Regards.
Although is possible to intercept the html rendering in a most low level of ASP MVC, even ASP.NET roots, I also think that the most adequate place to do that would be with a customized html helper. Unfortunately we depend from all others programs to never use the others helpers in this project.
Render with a customized html helper is a lot more easy than intercept the rendering, parse it and edit it.
Well, if someone has anyone suggestion, please tell us.
I think that one way would make a html helper that should be used by all programmers, so this helper would render the "class id" conditionally matching each action rendered to the actions permitted to the current user.
Actually that's a great way. That's exactly what I would do: a custom HTML helper method to render those links. And then in your views:
@Html.AuthorizedActionLink("linkText", "action", new { id = "123" })
My main concern would be, how would you tell HtmlHelper that it's appropriate to use this rule or not ?
This breaks away from the concerns that HtmlHelper should be concerned with.
Darin has just posted my suggestion though, create your own HtmlHelper or add your own extension methods to it.
Edit: Microsoft have a good link about this:
http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
精彩评论