且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何切换在MVC5 _layout视图

更新时间:2022-10-18 19:19:50

是的,你在你的问题了办法,我们可以做这样还,其他的简单有效的方法是:

我们可以通过使用下面code返回从的ActionResult布局覆盖缺省布局呈现

 公众的ActionResult指数()
{
 RegisterModel模式=新RegisterModel();
 VAR布局=;
 //这里只是检查你的条件,而不是视图,从这里返回一个适当的布局
 布局=〜/查看/共享/ _BlueLayout.cshtml
 返回视图(指数,布局,模型);
}

或相反在View应用条件只是把条件控制器,而不是为:

控制器:

 公众的ActionResult指数()
{
 RegisterModel模式=新RegisterModel();
 //这里只是检查你的条件,而不是视图,从这里把适当的布局Viewbag
 Viewbag.layout =〜/查看/共享/ _BlueLayout.cshtml
 返回查看(「指数」,型号);
}

查看:

  @ {
  布局= Viewbag.layout;
}

I Have a Table that contains different color of themes and I have define the _Layouts and css, I have apply the css to the their respectful layout.

e.g _LayoutBlue _LayoutGreen

I want to Check using a switch statement that when a user logins before rendering the view it should check the theme colour ID the user Choosed while creating an account and Apply to the User View

the question is, Is it Possible for me to do that from the Login controller so as to control the rendering layout based on the user theme colour in the database table

e.g is

    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;
   }

Yes the way you showed in your question ,we can do like that also ,other easy and effective way is :

We can override the default layout rendering by returning the layout from the ActionResult by using the below code:

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 Instead of applying condition in View just put conditions in Controller instead as :

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);
}

View :

@{
  Layout = Viewbag.layout;
}