109221793
109221793

Reputation: 16897

C# - If statement to dynamically determine which master page to use - MVC 2

I have two master pages in my C# MVC application. What I would like to be able to do is use one, or the other depending on the users 'role'. Something similar to this (obviously with a little more validation etc):

<% 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>" %>
<% } %>

I've seen answers where this can be done to elements of a page, for example a menu, an image, etc. Is it possible to do it for the entire master page? In my situation, depending on the role, different css, images, colours will be used so it is necessary to use a different master page.

If anyone could help I'd be very grateful, or if anyone has any alternative (and probably better) solutions I'd also be grateful.

Thanks.

Upvotes: 1

Views: 2042

Answers (3)

dotnetstep
dotnetstep

Reputation: 17485

As you are using ASPX View in ASP.net MVC Application. ASP.net MVC ASPX ( Webform) view still derive from Page class so you can use following code in your 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>

Upvotes: 3

Flater
Flater

Reputation: 13783

I would suggest making the selection in your Masterpage file rather than selecting which masterpage file to use.

Upvotes: 0

Tomas Voracek
Tomas Voracek

Reputation: 5914

You can change it dynamically via ViewMasterPage.MasterPageFile.

Upvotes: 1

Related Questions