how to override a views Layout declaration

前端 未结 4 1293
無奈伤痛
無奈伤痛 2021-01-19 15:43

In asp.net MVC 3 is there a way to override the Layout declaration set in a view from a controller or action filter?

@{
    Layout = \"~/Views/Shared/_Layout.cshtm         


        
相关标签:
4条回答
  • 2021-01-19 16:17

    Another place where you can control the layout is in the _ViewStart.cshtml.

    Here, you can do the logic you need and programatically specify which layout to use. This allows you to place the logic in only one place and keep it out of the view.

    @{
        if(myBusinessRule)
        {
           Layout = "~/Views/Shared/_Layout.cshtml";
        }
        else
        {
           Layout = "~/Views/Shared/_SecondaryLayout.cshtml";
        }
    }
    

    Blog post where it was introduced by Scott Gu

    0 讨论(0)
  • 2021-01-19 16:18

    Use ViewBag when you need to change the layout call an action and put the new layout (even null) in viewbag.

    @{
       Layout = ViewBag.layout;
    }
    

    and inside the action

    if(something)
       ViewBag.layout = "~/Views/Shared/whatever.cshtml";
    else
       ViewBag.layout = null;
    
    0 讨论(0)
  • 2021-01-19 16:20

    sorry to simply add a ref to one of my previous posts on this subject, but have a look here, it may give a wider view (pun intended) on the topic:

    Where and how is the _ViewStart.cshtml layout file linked?

    0 讨论(0)
  • 2021-01-19 16:22

    You can create an action filter to override Layout file, but if you want to remove it, you will have to create an empty layout file instead of assigning the Master property to null. Like this:

    public class OverrideLayoutFilter : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var view = filterContext.Result as ViewResult;
            view.MasterName = "_LayoutEmpty";
            base.OnResultExecuting(filterContext);
        }
    }
    

    Controller:

    public class HomeController : Controller
    {
        [OverrideLayoutFilter]
        public ActionResult Index()
        {
            return View();
        }
    }
    

    Now your new layout file needs to be placed in SharedFolder and you only put the RenderBody function inside

    _LayoutEmpty.cshtml

    @RenderBody()
    

    Note: If you have sections defined in a view that you want to override layout you will also have to define those sections with an empty content.

    0 讨论(0)
提交回复
热议问题