如何指定在ASP.NET MVC 3剃须刀ViewStart文件不同的布局? [英] How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

查看:165
本文介绍了如何指定在ASP.NET MVC 3剃须刀ViewStart文件不同的布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序2个独立的布局。让说一个是网站的公共部分,另一种是成员方。

I would like to have 2 separate Layouts in my application. Let say one is for the Public section of the website and the other is for the Member side.

为了简单起见让我们说了每种论文网站的逻辑被整齐包裹成2个不同的控制器。

For simplicity lets say all the logic for each of theses sites is wrapped neatly into 2 distinct controllers.


  • PublicController

  • StaffController

和他们各自对所有下的每个视图相应的布局。

And that they each have a corresponding Layout for all the View under each.


  • _PublicLayout.cshtml

  • _StaffLayout.cshtml

我如何使用_ViewStart.cshtml文件来指定公用下的所有视图的/动作使用PublicLayout和一切工作人员下使用StaffLayout?

How do I use the _ViewStart.cshtml file to specify that all View's / Action under "Public" use the PublicLayout and everything under "Staff" use the StaffLayout?

谢谢!

推荐答案

您可以把 _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();
}

这篇关于如何指定在ASP.NET MVC 3剃须刀ViewStart文件不同的布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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