How To Switch _Layout view in MVC5

2019-08-27 09:21发布

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

1条回答
祖国的老花朵
2楼-- · 2019-08-27 09:50

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;
}
查看更多
登录 后发表回答