【问题标题】:Dynamic change ViewStart layout path in MVC 3MVC 3 中动态改变 ViewStart 布局路径
【发布时间】:2011-12-07 17:34:28
【问题描述】:

在我的 MVC 项目中有 2 个区域,即管理员和客户端,我需要为客户端动态配置布局,在 _ViewStart(在客户端)文件中将为所有客户端页面设置布局。

Layout = "~/Views/Shared/_Layout.cshtml";

所以如果我们需要更改客户端布局,我们可以在_ViewStart 文件中更改cshtml 文件的布局路径对吗?我找不到如何更改 ViewStart 文件或在这种情况下是否有其他解决方案。

感谢您的帮助:)

【问题讨论】:

    标签: asp.net-mvc-3 model-view-controller


    【解决方案1】:

    请记住,@{ ... } 中的任何内容都被视为代码。因此,在其中放置一个条件来更改它的继承方式应该是一件简单的事情:

    @{
      Layout = "~/Views/Shared/_Layout.cshtml";
      if (User.Current.IsAuthenticated) {
        Layout = "~/Views/Shared/_AdminLayout.cshtml";
      }
    }
    

    虽然您可能会更好地查看主题(并且拥有管理员/用户主题)。或者,您可以让您的 _Layout.cshtml 更智能,并让它根据条件处理不同的视图。

    另请参阅:MVC3 Razor - Is there a way to change the Layout depending on browser request?

    【讨论】:

      【解决方案2】:

      您的问题没有足够的信息为您提供完整的代码示例。

      但基本上你可以做到这一点

      if (InsertIsAdminLogicHere) {
           Layout = "~/Views/Shared/_AdminLayout.cshtml";
      } else {
           Layout = "~/Views/Shared/_Layout.cshtml";
      }
      

      如果您向我们展示您如何确定管理员,我们可以提供更多帮助。

      希望这会有所帮助

      【讨论】:

        【解决方案3】:

        您可以利用嵌套布局。创建一个基本控制器并从该控制器驱动所有控制器。

        public class ControllerBase : Controller
        {
            public ControllerBase()
            {
                ViewBag.Theme = "~/Views/Shared/Default/Views/_Layout.cshtml";
            }
        }
        
        public class HomeController : ControllerBase
        {
            public ActionResult Index()
            {
        
                return View();
            }
        }
        

        _ViewStart.cshtml(不要在这个文件中做任何改变)

        @{
            Layout = "~/Views/Shared/_Layout.cshtml";
        }
        

        视图/共享/_Layout.cshtml 这是 Asp.NET Mvc 的默认布局文件。清空并替换这些行。

        @{ 
            Layout = ViewBag.Theme;
        }
        
        @RenderBody()
        

        您可以对区域进行这种修改。您可以从数据库或任何您想要的地方获取 BaseController 中的活动模板信息。

        顺便说一句,如果您想将视图放在 ~/Views 文件夹之外,请搜索 ThemeableRazorViewEngine

        【讨论】:

          【解决方案4】:

          在视图/_ViewStart.cshtml中

          @{    
          object multiTenant;
          if (!Request.GetOwinContext().Environment.TryGetValue("MultiTenant", out multiTenant))
          {
              throw new ApplicationException("Could not find tenant");
          }
          Layout = "~/Views/"+ ((Tenant)multiTenant).Name + "/Shared/_Layout.cshtml";
          }
          

          【讨论】:

            猜你喜欢
            • 2011-07-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多