ASP.NET MVC 2 technique to hide a part of a view based on user permissions
What's the best technique to hide part of a view depending of the credentials of the user?
To explain my self li开发者_JAVA百科ttle better and as example i have the following code in my view:
<%= this.Model.Name %> <%=Html.ActionLink("Edit",....)%>
And i would like to hide the edit button for those that aren't administrators for instance...
Could you give me a hand?
Thanks a lot in advance.
Best Regards.
There are more ways of doing this, but you have to consider to follow DRY while doing it. And also taking into consideration that your views shouldn't be too complex.
Less obvious way
Write Html extension methods (for those elements that you need) that also take a set of rights as a parameter and would render their content based on them. Like:
<%= Html.ActionLink(new PermissionRight[] { PermissionRight.Edit, PermissionRight.Create }, "Edit", ...) %>
This way you'll be able to supply all rights that can expose such functionality, and it would be generic for all views/partials... If you define your PermissionRight
enumeration as flags, you could supply them without arrays.
The usual (obvious) way
You'd either write your own base view or base controller class and expose your user (or at least data you need) directly in it. And of the correct type, so no casting would be needed.
Then just use those like (this one has base view class):
<% if (this.User.HasWritePermission) %>
<% { %>
<%= Html.ActionLink("Edit", ...) %>
<% } %>
You can see that this solution takes more lines to accomplish the same task than the first one, thus polluting your views with much more code than necessary.
In your controller, when you authenticate a user, you can pass additional members to the view like isAdmin in the Model object.
If the user is admin, then set isAdmin to true.
In your view, render the Edit button if isAdmin is true.
精彩评论