how to override a views Layout declaration

前端 未结 4 1328
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题