开发者

Hide Admin Links from everyone

开发者 https://www.devze.com 2023-03-23 06:16 出处:网络
I am using asp.net mvc with r开发者_如何学Pythonazor. How can I hide links which are only for admins?You could declare a boolean property on your view model:

I am using asp.net mvc with r开发者_如何学Pythonazor. How can I hide links which are only for admins?


You could declare a boolean property on your view model:

public class MyViewModel
{
    public bool IsAdmin { get; set; }

    ... some other model properties
}

and inside your view:

@if (Model.IsAdmin)
{
    <!-- show the link that only administrators are supposed to see -->
    @Html.ActionLink("Do something very special", "Bar")
}

and of course inside the controller action rendering this view you would populate this view model:

[Authorize]
public ActionResult Foo()
{
    var model = new MyViewModel
    {
        IsAdmin = User.IsInRole("Admin")
    };
    return View(model);
}

Obviously the Bar action which only administrators could invoke should be decorated with the Authorize attribute as well:

[Authorize(Roles = "Admin")]
public ActionResult Bar()
{
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消