2009-09-13 85 views
5

以任何機會,有沒有簡單的方法來設置特定的控制器內的所有操作的默認馬西德威?ASP.NET MVC - 設置主視圖相應地與控制器

例如,如果我有的HomeController我希望所有裏面的行動來繼承的Site.Master爲默認值,但如果我是裏面AccountsController我希望所有的行動繼承管理員。掌握等..

我成功做到這一點的:

return View("viewName", "masterName", objectModel); 

但是,這樣做我有我每次調用瀏覽方法時,應用它。

我一直在尋找在軌道上簡單的東西一樣,我們可以宣佈:

class HomeController < ApplicationController 

    layout 'site' 

    def index 
    end 

    def create 
    ... 

end 

class AccountsController < ApplicationController 

    layout 'admin' 

    def index 
    end 

    def create 
    ... 

end 

這可能嗎?

在此先感謝

回答

6

你可以在控制器類中重寫OnActionExecuting。

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    ViewData["MasterfileToUser"] = "site"; 
}  

或者,如果你喜歡,你可以把它變成一個ActionFilterAttribute你可以申請在控制器或行動水平

using System; 
using System.Web.Mvc; 
public class MasterFileFilterAttribute : ActionFilterAttribute 
{ 
    public string Master { get; set; } 

    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    {   
      if (filterContext.Result is ViewResult) 
        ((ViewResult)filterContext.Result).MasterName = Master; 
    } 
} 

,你再依次使用像這樣:

[MasterFileFilterAttribute(Master = "site")] 
public class HomeController : Controller 
{ 
    // Action methods 
} 
+0

喜Olle,謝謝你的回答。只有一件事,我沒有抓住,是一個ViewData [「MasterfileToUser」]如何反映主文件?那我應該怎麼做才能使其正確加載主文件? – zanona 2009-09-13 19:48:36

+1

我從視圖數據中分配它不起作用。我採取了第二次刺,但我目前不在哪裏我可以測試這個地方。在OnActionExecuted結果(一個ViewResult實例)可用它有一個Masterpage屬性,所以我現在在那裏分配它。請測試自己:) – olle 2009-09-13 20:17:40

+0

歐萊只要一想到這裏... 現在每次我把它拋出一個錯誤的方法RedirectToAction: 無法投類型的對象System.Web.Mvc.RedirectToRouteResult爲鍵入「System.Web程序。 Mvc.ViewResult」。 並使用MasterFileFileAttribute類。任何想法如何解決它? 謝謝 – zanona 2009-09-14 08:31:47