0
過去幾天我一直在想這件事,並想知道其他人對此的看法。我想實現一些基於用戶所屬角色的內容。我們的應用程序使用HTTP頭來接收角色信息。在MVC中,我應該讓控制器處理角色檢測,然後將布爾值傳遞給viewmodel。實現邏輯來提供基於角色的查看數據
視圖模型:
public class ProductViewModel
{
public Product MyProduct { get; set; }
public bool IsAdmin { get; set; }
public bool IsSuperAdmin { get; set; }
}
控制器:
public class ProductController : Controller
{
public ActionResult Info()
{
//get product information here
ProductViewModel pvm = new pvm();
pvm.Product = theProduct;
pvm.IsAdmin = checkAdminAccess(); //This would return a bool if they had access
pvm.IsSuperAdmin = checkSuperAdminAccess();//This would return a bool if they had access
return View(pvm);
}
}
查看:
@if(Model.IsAdmin == true || Model.IsSuperAdmin == true)
{
//Render Content for admin (Either directly or via Partial View)
}
@if(Model.IsSuperAdmin == true)
{
//Render Superadmin content (Either directly or via Partial View)
}
//Implement other Product Stuff Here
或者它會更好地創建一個局部視圖,以及如何在視圖中的邏輯。這似乎是涉及較少的工作。
@if (Request.Headers.AllKeys.Contains("role")){
ViewBag.Role = Request.Headers["role"].ToString();
}
...
@if(ViewBag.Role == "Admin" || ViewBag.Role == "SuperAdmin")
{
@Html.Partial("AdminPartial")//Or Render Code Directly?
if(ViewBag.Role == "SuperAdmin")
{
@Html.Partial("SuperAdminPartial")//Or Render Code Directly?
}
}
//Implement other Product Stuff Here
這樣做還有什麼額外的好處,我應該直接渲染內容還是使用局部視圖還是不重要?或者我錯過了其他一些應該完成的方法?