如何切换在MVC5 _layout视图 [英] How To Switch _Layout view in MVC5

查看:1157
本文介绍了如何切换在MVC5 _layout视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如
_LayoutBlue
_LayoutGreen

我想用一个switch语句,当用户登录渲染视图前应该检查的主题颜色ID的用户选用,同时创建一个帐户,并应用到用户视图检查

问题是,是否有可能为我做的,从登录控制器,以便根据数据库表中的用户主题颜色

控制呈现布局

例如为

 开关(的ThemeID)
   {
    情况1:
        布局=〜/查看/共享/ _BlueLayout.cshtml
        打破;
    案例2:
        布局=〜/查看/共享/ _MagentaLayout.cshtml
        打破;
    默认:
         布局=〜/查看/共享/ _Layout.cshtml
        打破;
   }


解决方案

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

我们可以通过使用下面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;
}

这篇关于如何切换在MVC5 _layout视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆