MVC 2 应用程序 - 设置动态母版页

发布于 2024-12-26 22:51:48 字数 650 浏览 5 评论 0原文

我希望能够根据 MVC 2 应用程序中当时的 URL 设置母版页。

我已经在我的视图中插入了 C# 代码,并且已经做到了这一点 -

<script language="C#" runat="server">
    protected void Page_PreInit(object sender, EventArgs e)
    {
        var hostName = HttpContext.Current.Request.Url.Host.ToString();
        if (hostName == "localhost")
        {
            this.MasterPageFile = "~/Views/Shared/Site.Master";
        }
        else
        {
            this.MasterPageFile = "~/Views/Shared/Administrator.Master";
        }
    }
</script>

上面的 IF 语句用于测试,实际上我将从数据库中提取母版页名称,但这很好。

如果可能的话,我显然不想将上面的代码插入到每个视图中。是否可以从 global.asax 文件或类似文件中进行设置?

I want to be able to set a master page depending on the URL at the time in an MVC 2 application.

I've inserted C# code in my Views and I've gotten this far -

<script language="C#" runat="server">
    protected void Page_PreInit(object sender, EventArgs e)
    {
        var hostName = HttpContext.Current.Request.Url.Host.ToString();
        if (hostName == "localhost")
        {
            this.MasterPageFile = "~/Views/Shared/Site.Master";
        }
        else
        {
            this.MasterPageFile = "~/Views/Shared/Administrator.Master";
        }
    }
</script>

The IF statement above was for testing, in reality I'll be pulling the master page names from a database but that will be fine.

If possible, I would obviously rather not inserting the code above onto each and every view. Is it possible to set this from the global.asax file or similar?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文