如何在MVC2下以编程方式设置母版页

时间:2010-11-17 20:14:49

标签: asp.net-mvc asp.net-mvc-2 master-pages

在普通的ASP.NET中,这是一项简单的工作......只需覆盖Page_PreInit并完成!

但是如何在 ASP.NET MVC2

下完成此操作

2 个答案:

答案 0 :(得分:5)

在ASP.NET MVC中更简单,只需将母版页的名称作为第二个参数传递:

return View("MyView", "MyMasterPage");

当然,您也可以创建自己的System.Web.Mvc.ViewPage并在那里更改母版页。

答案 1 :(得分:2)

如果你有一些在管理员和用户站点之间共享的动作,你也可以在覆盖(在控制器或基本控制器中)中执行此操作:

protected override ViewResult View(string viewName, 
                                   string masterName, object model)
{

    // we share some views that aren't partialviews
    // therefore, we have to ensure that the Shareholder master template
    // is ALWAYS attached to the logged in user if they aren't an admin user
    bool userIsAdmin = IsAuthorised("Admin");

    if (!userIsAdmin) // then flip the masterpage to Shareholder.Master
    {
        masterName = "Shareholder";
    }

    return base.View(viewName, masterName, model);
}

另一种悬挂自己的方式,我的意思是,给猫咪涂上皮肤:)