0

I'm used to create custom attributes to prevent different access level to reach some methods in a controller:

[AuthorizeUser(AccessLevel = "Administrator")]
public ActionResult Index()
{
    return View("Index");
}

But now I would like to use the same custom attribute in a view. The goal would be to display some HTML when you are an administrator for example.

It sounds strange but I found nothing about that. Any help would be appreciated.

4

2 回答 2

1

我不确定这是否是正确的方法,但这可能会奏效。

解决方案1

例如,您可以boolean在模型中检查用户是否具有特定角色,然后基于该模型创建视图。

public class MyViewWithCustomAuthentication
{
  ....
  public bool IsAdmin{get;set;}
  ...
}

在您的控制器中,您可以检查用户是否处于特定角色

public ActionResult Index()
{
    var myView = new MyViewWithCustomAuthentication();
    myview.IsAdmin = false;
    if(User.IsInRole("Admin"))
    {
       myView.IsAdmin = true;
    }

    return View(myView);
}

然后在视图中

@model MyViewWithCustomAuthentication
....
@if(Model.IsAdmin == true)
{
  //show HTML
}
else
{
  //hide HTML
}
....

在这里,您将拥有一个视图,但正如我所提到的,您可能需要对视图模型进行一些小的更改。

解决方案 2

另一种方法可能是检查用户是否处于某个角色并根据要求为不同的角色创建不同的视图。通过这种方式,您可以显示所需的 HTML,但最终您将获得不同的视图。

public ActionResult Index()
{       
    if(User.IsInRole("Admin"))
    {
       return View("ViewForAdmin")
    }

    return View("ViewForNonAdmin");
}

如果有人有任何建议,请随时编辑或评论。

于 2014-05-27T17:31:08.347 回答
0

您应该能够使用局部视图和RenderAction.

[ChildActionOnly]
[AuthorizeUser(AccessLevel = "Administrator")]
public ActionResult AdminPartial() {
  return PartialView();
}

在视图内部,您需要该管理 HTML 片段。

@{Html.RenderAction("AdminPartial");}
于 2014-05-28T03:29:40.057 回答