且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何指定在ASP.NET MVC 3剃须刀ViewStart文件不同的布局?

更新时间:2023-02-14 18:02:28

您可以把 _ViewStart.cshtml 之内的文件/查看/公这将覆盖默认一个在 /浏览次数文件夹,并指定所需的布局文件夹:

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

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

打个比方,你可以把另一个 _ViewStart.cshtml 文件中的内/查看/员工文件夹:

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

您也可以指定要使用的布局返回控制器动作内部的视图时,但这是每行动:

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

另一种可能是一个自定义操作过滤器将覆盖布局。正如你可以看到很多的可能性,实现这一目标。由你来选择哪一个最适合你的方案。

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.

更新:

由于在评论部分要求这里的一个动作过滤器,它会选择一个母版页的例子:

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

再装饰一个控制器或与该自定义属性指定你想要的布局动作:

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}