如何在MVC5中切换_Layout视图

时间:2014-08-26 16:11:55

标签: css layout asp.net-mvc-5

我有一个包含不同颜色主题的表,我已经定义了_Layouts和css, 我已经将css应用于他们尊重的布局。

e.g _LayoutBlue _LayoutGreen

我想使用switch语句检查当用户在渲染视图之前登录时,应检查用户在创建帐户时选择的主题颜色ID并应用于用户视图

问题是,我是否可以从Login控制器执行此操作,以便根据数据库表中的用户主题颜色控制渲染布局

例如

    switch(ThemeID)
   {
    case 1:
        Layout = "~/Views/Shared/_BlueLayout.cshtml";
        break;
    case 2:
        Layout = "~/Views/Shared/_MagentaLayout.cshtml";
        break;
    default:
         Layout = "~/Views/Shared/_Layout.cshtml";
        break;
   }

1 个答案:

答案 0 :(得分:1)

是的,你在问题中的表现方式,我们也可以这样做,其他简单有效的方法是:

我们可以通过使用以下代码从ActionResult返回布局来覆盖默认布局渲染:

public ActionResult Index()
{
 RegisterModel model = new RegisterModel();
 var layout="";
 //Just check your conditions here instead in view and return a appropriate layout from here
 layout="~/Views/Shared/_BlueLayout.cshtml";
 return View("Index", layout , model);
}

OR而不是在View中应用条件而只是将条件放在Controller中而不是:

控制器:

public ActionResult Index()
{
 RegisterModel model = new RegisterModel();
 //Just check your conditions here instead in view and put appropriate layout in Viewbag from here
 Viewbag.layout="~/Views/Shared/_BlueLayout.cshtml";
 return View("Index", model);
}

查看:

@{
  Layout = Viewbag.layout;
}