【问题标题】:C# - If statement to dynamically determine which master page to use - MVC 2C# - If 语句动态确定使用哪个母版页 - MVC 2
【发布时间】:2011-12-19 11:19:08
【问题描述】:

我的 C# MVC 应用程序中有两个母版页。我想做的是使用一个,或者另一个取决于用户的“角色”。与此类似的东西(显然需要更多验证等):

<% if(User.IsInRole("One")) { %>
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/One.Master"
    Inherits="System.Web.Mvc.ViewPage<MyApp.Data.ProductData>" %>
<% } else if { %>
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Other.Master"
    Inherits="System.Web.Mvc.ViewPage<MyApp.Data.ProductData>" %>
<% } %>

我已经看到可以对页面元素执行此操作的答案,例如菜单、图像等。是否可以对整个母版页执行此操作?在我的情况下,根据角色,将使用不同的 css、图像、颜色,因此有必要使用不同的母版页。

如果有人可以提供帮助,我将不胜感激,或者如果有人有任何替代(可能更好)的解决方案,我也将不胜感激。

谢谢。

【问题讨论】:

    标签: c# asp.net-mvc-2 master-pages


    【解决方案1】:

    当您在 ASP.net MVC 应用程序中使用 ASPX 视图时。 ASP.net MVC ASPX(Webform)视图仍然派生自 Page 类,因此您可以在 你的 aspx 视图。

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage"  %>
    <script language="C#" runat="server">
        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (User.IsInRole("Admin"))
            {
                this.MasterPageFile = "~/Views/Shared/Site2.Master";
            }
            else
            {
                this.MasterPageFile = "~/Views/Shared/Site.Master";
            }
        }
    </script>
    

    【讨论】:

      【解决方案2】:

      您可以通过ViewMasterPage.MasterPageFile动态更改它。

      【讨论】:

      • 这个答案不错,但或许你可以用相关的代码sn-p来补充一下。
      【解决方案3】:

      我建议选择in您的母版页文件,而不是选择要使用的母版页文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-22
        • 1970-01-01
        • 2017-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多