asp.net-mvc ASP.NET MVC 检查视图内的角色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4610749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:41:25  来源:igfitidea点击:

ASP.NET MVC Check role inside view

asp.net-mvcuser-roles

提问by Cameron

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>
<%= } %>

回答by Pa?out

@if (this.User.IsInRole("Administrator"))
{

}

回答by CRice

<% 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.

然而,在我看来,这是一个可怕的想法。最好让 ViewData 或 Model 代表视图要显示什么,视图可以简单地检查视图数据。控制器基类或动作过滤器可以非常简单地重复使用这一点,并允许代码存在于一个地方。

回答by CRice

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.

我同意大多数其他人的意见,如果您愿意,应该由控制器或其他业务服务“预先确定”提供这些数据,而视图只是尽可能多地使用 html 标记和语言控制结构来“充实”页面”使用其他典型的网页构建工具,例如 jquery、css 等。