Skip to main content
 首页 » 编程设计

C#之动态确定要使用哪个母版页的 If 语句之MVC 2

2024年02月23日12soundcode

我的 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、图像、颜色,因此有必要使用不同的母版页。

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

谢谢。

请您参考如下方法:

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

<%@ 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>