2011-07-25 218 views
1

我使用的是帶有剃鬚刀的asp.net mvc。我怎樣才能隱藏只有管理員的鏈接?隱藏所有人的管理鏈接

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

    ... some other model properties 
} 

和您的視圖中:

+0

你如何確定某人是否是管理員? –

回答

1

你可以在你的視圖模型聲明一個布爾屬性

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

過程中,控制器的動作裏面和渲染這種觀點,你會填充此視圖模型:

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

顯然只有管理員可以在我的酒吧行動我nvoke也應使用Authorize屬性進行裝飾:

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