开发者

Hide Admin Links from everyone

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜