如何在视图中使用MVC角色权限?

如何根据角色中的一组用户在视图中应用权限。

例如,如何为角色编辑器显示“创建文章”按钮并将其隐藏为角色Reader?

最佳实践是让Controller在ViewModel上设置属性,然后View可以检查这一点,它也使逻辑更容易测试。

它的模型工作是与视图的沟通者。
然后安全逻辑不会泄漏到View中。

在您的控制器中,您可以执行以下操作:

model.IsEditor = User.IsInRole("editor") model.IsReader = User.IsInRole("reader") 

然后,如果您查看,您可以执行以下操作:

 @if (model.IsEditor) { // show editor button } @if (model.IsReader) { // show reader button } 

对此有两种思想流派。

一所学校说你为角色创建了单独的视图。 因此,您可以创建RoleEditor视图和RoleReader视图。 而且,在相对简单的应用程序中,这可能是最好的方法。

如果您的观点更复杂,并且需要基于角色的“即时”渲染,那么您可以采用更像Ralph建议的方法。 你做这样的事情:

 public ActionResult Index() { // IsUserAnEditor is a placeholder for a method to determine whether the user // is an editor based on whatever role technology you're using. MyModel model = new MyModel { IsEditor = IsUserAnEditor() } return View(model); } 

然后在您的视图中,您有这样的代码:

 @model MyModel .... @if(Model.IsEditor) { // Code to add the "Edit" link, this is just an example, customize for your needs  @Html.ActionLink("Edit", "Edit", "MyController", new { id=Model.ID })  }