如何覆盖视图布局声明 [英] how to override a views Layout declaration

查看:111
本文介绍了如何覆盖视图布局声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在asp.net MVC 3中,是否有一种方法可以覆盖从控制器或动作过滤器获取的视图中设置的布局声明?

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.cshtml";
}

我尝试覆盖OnResultExecuted或OnResultExecuting中的MasterName属性,如下面的代码片段一样,无济于事.

I have tried overriding the MasterName property in the OnResultExecuted or the OnResultExecuting like the following code snippet, to no avail.

public override void OnResultExecuting(ResultExecutingContext filterContext)
{
    var view = filterContext.Result as ViewResult;
    view.MasterName = null;
}

推荐答案

您可以创建一个操作过滤器来覆盖布局文件,但是如果要删除它,则必须创建一个空的布局文件,而不是分配主文件属性为null.像这样:

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);
    }
}

控制器:

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

现在,您需要将新的布局文件放置在SharedFolder中,并且只将RenderBody函数放在其中

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

_LayoutEmpty.cshtml

_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.

这篇关于如何覆盖视图布局声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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