在Controller方法中获取布局名称 [英] Get Layout name in Controller method

查看:121
本文介绍了在Controller方法中获取布局名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVC 5,并且想在我的MVC控制器中覆盖下面的View方法

I'm using MVC 5 and want to override the below View method in my MVC controller

protected internal virtual ViewResult View(string viewName, string masterName, object model)

我可以有许多不同的布局视图,因此想在运行时获取当前布局名称,并将其传递给覆盖的视图方法.如何在运行时在控制器中获取布局名称?

I can have a number of different layout views so want to get the current layout name at runtime and pass it to the overriden view method. How do I get the layout name at runtime in the controller?

编辑 我认为不需要为需要执行的操作创建自定义视图引擎.我基本上只想跨多个方法和控制器设置ViewBag值,并且不想重复自己.我在运行时有viewName和model值,只是没有要作为masterName参数传递的布局名称

EDIT I don't think I need to create a custom view engine for what I need to do. I basically only want to set a ViewBag value across multiple methods and controllers and don't want to repeat myself. I have the viewName and model values at runtime, just don't have the layout name to pass as the masterName parameter

protected override ViewResult View(string viewName, string masterName, object model)
{
ViewBag.SomeValue = GetValue();            
return base.View(viewName, masterName, model);
}

推荐答案

您在运行时使用什么来做出决定-是否存在一些标识符, 会告诉你要使用哪个大师???也许您可以进行切换?

What are you using to make the decision at runtime - Is there some identifier that will tell you which Master to use??? Maybe you can make a Switch?

Switch (loggedInUser.SomeSpecialValue)
{
Case: "value1":
return "_Layout1.cshtml";
}

您还打算如何决定要显示哪个版式?

How else were you planning to make the decision as to which Layout to show?

好的,可以扩展上述想法-也许像这样的东西可以帮助您:

Okay extending the above idea - Maybe something like this can help you:

RouteConfig

routes.MapRoute(
                name: "Default",
                url: "{layout}/{controller}/{action}/{id}",
                defaults: new { layout = "default", controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

HomeController

protected override ViewResult View(string viewName, string masterName, object model)
        {
            var layout = RouteData.Values["layout"].ToString();

            switch (layout)
            {
                case "default":
                    return base.View(viewName, "_layout", model);
                case "test":
                    return base.View(viewName, "_layout2", model);
            }

            return base.View(viewName, masterName, model);
        }

观看次数 根据需要创建布局"视图,并将其添加到共享"文件夹和switch语句中.

Views Create Layout views as required, and add them to the Shared folder and the switch statement.

测试URL的

http://localhost:64372/ -> Default Layout
http://localhost:64372/default/home/index
http://localhost:64372/test/ -> 2nd Layout
http://localhost:64372/test/home/index

希望这可能对您有用?

这篇关于在Controller方法中获取布局名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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