ASP.NET MVC Check role inside view
In my View I have some admin links that I would like to hide and show based开发者_高级运维 on user role how can do this inside the view e.g.
<%= if(CHECK IF USER ROLE ADMIN) { %>
<div class="tools">
<ul>
<li class="edit"><%= Html.ActionLink("Edit", "Edit", new { id = Model.storyId }) %></li>
<li class="delete"><%= Html.ActionLink("Delete", "Delete", new { id = Model.storyId }) %></li>
</ul>
</div>
<%= } %>
@if (this.User.IsInRole("Administrator"))
{
}
<% if (Page.User.IsInRole("Admin")){ %>
<%}%>
However this is a terrible idea in my opinion. It is better to let the ViewData or Model represent what the view is to display, and the view can simply check the view data. A controller base class or an action filter can make repetitive use of this very simple and allow the code to exist in one place.
I agree with most others that this data should be provided "pre-determined", if you will, by the controller or other business services whereas the View simply uses, as much as possible, html markup and language control structures to "flesh out the page" using other typical web page building goodies such as jquery, css, etc. etc.
精彩评论