How To Switch _Layout view in MVC5

六月ゝ 毕业季﹏ 提交于 2019-12-13 03:36: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:


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


来源:https://stackoverflow.com/questions/25510465/how-to-switch-layout-view-in-mvc5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!