开发者

Display/hide menu items depending on logged on user

开发者 https://www.devze.com 2022-12-23 21:08 出处:网络
In my web app, I would like to show an \"Admin\" menu link only to users who have been added to the database as an administrator.

In my web app, I would like to show an "Admin" menu link only to users who have been added to the database as an administrator.

What would be the best way to do this in ASP.NET MVC 2?

At the moment, I am doing it by 开发者_如何学Cchecking whether the user exists in the Admin database table for every page. Obviously, there must be a better way to do this.

If it helps, I am using Windows Auth.


You could probably save the admin state in a session variable or something, but it seems more appropriate to create a partial view with the menu (if you haven't already) and just have the check in there. You'll still have a database call for it on each page request, but no duplication of code. And unless you have performance issues right now, one extra call really isn't that big of a deal.

If you do have performance issues, make sure you optimize your own code, have all the correct indices on the db etc. A lot of performance gain (especially in db related problems) can usually be made by re-structuring how things are done, instead of what is done.

UPDATE:
In ASP.NET MVC 2 there is actually an even better way you could do this, combining Html.RenderAction() and AuthorizeAttribute (or possibly write your own inherited attribute that sets a flag instead of returning an error when the user is not authorized). That way you would minimize view logic, and conform better to the MVC principles.

0

精彩评论

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

关注公众号