2012-09-10 24 views
0

將一個webforms應用程序轉換爲mvc 4.該應用程序在主頁面代碼隱藏中執行相當數量的處理以執行諸如根據用戶角色確定用戶可以或不能看到的內容,版本位於組件的頁面底部等所有服務器端。mvc 4在佈局中處理

我知道處理不是在代碼隱藏中,而是在發送到視圖的數據的控制器中。但它不是我清楚如何在_Layout.cshtml

非常感謝

回答

0

有些事情,你也許能夠做的是使用一個基控制器,並覆蓋了OnActionExecuting方法,然後使用ViewBag動態完成屬性值傳遞給你的_Layout.cshtml

public abstract class BaseController : Controller 
{ 
    protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     var user = filterContext.Controller.ControllerContext.RequestContext.HttpContext.User; 
     // do whatever you need to do 
     ViewBag.CanUserViewSomethingSecret = user.Identity.Name == "Kermit"; 
    } 
} 

你需要這個基地控制器應用程序控制器擴展

public class HomeController : BaseController 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 
} 

然後在你的_Layout.cshtml您可以訪問ViewBag屬性是這樣的...

@if(ViewBag.CanUserViewSomethingSecret != null && (bool) ViewBag.CanUserViewSomethingSecret == true) 
    { 
     <p>Secret</p> 
    } 
+0

非常好,謝謝! – user542319

+0

沒問題:-)它是否回答你的問題? – simonlchilds