change Layout based on type of User role

14,317

Solution 1

You just need to modify the /Views/_ViewStart.cshtml file.

@{
    if (this.User.IsInRole("Admin") || !this.User.Identity.IsAuthenticated) {
        Layout = "~/Views/Shared/_Layout.cshtml";
    } else {
        Layout = "~/Views/Shared/_LayoutUser.cshtml";
    }
}

You didn't mention what should happen if no user is logged in, so I added the check and just sent them to the _Layout.cshtml view. You should change the logic as needed for your application.

Solution 2

You need to first work in global.asax file add the method Application_PostAuthenticateRequest . Then get your roles from database ex:

  roles = spRepository.GetUserRolByUsername(username)
then add this roles to HttpContext ex:

    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
                            new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));

Finally you can access role from your layout page:

     @if (HttpContext.Current.User.IsInRole("Administrator"))
            {
                Html.RenderPartial("AdminMenu");
            }
Share:
14,317
Kivan Ilangakoon
Author by

Kivan Ilangakoon

Updated on June 16, 2022

Comments

  • Kivan Ilangakoon
    Kivan Ilangakoon almost 2 years

    I am new to MVC, I looked through similar posts on stack, but they did'nt seem to help my problem. I have two roles Admin and User. When a person logs in, I want the layout to change based on whether the person had Admin privileges or User Privileges.

    My Admin Layout is _Layout.cshtml

    My User Layout is _LayoutUser.cshtml

    Is there something in my Login Controller that I can put which will change the layout based on the role of the User? The role of the user is specified in the Login table.

    id     LoginStudentNumber    LoginPassword      Role
    1           123456              123456          Admin
    2           234567              234567          Admin
    3           345678              345678          User
    4           456789              456789          User
    

    Login Controller:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using RMS.DAL;
    using RMS.Models;
    
    namespace RMS.Controllers
    {
        public class LoginController : Controller
        {
            RMSContext db = new RMSContext();
    
    
            [AllowAnonymous]
            public ActionResult Login(string returnUrl)
            {
                ViewBag.ReturnUrl = returnUrl;
                return View();
            }
    
            //
            // POST: /Account/Login
            [HttpPost]
            [AllowAnonymous]
            public ActionResult Login(Login model, int? LoginStudentNumber, string LoginPassword)
            {
    
    
                //RMS.Models.Login user = db.Logins.Find(LoginID);
                RMS.Models.Login user = db.Logins.FirstOrDefault(l => l.LoginStudentNumber == model.LoginStudentNumber);
    
    
                if (user == null)
                {
                   ViewBag.InvalidID = "Invalid User Id";
    
                    return View(model);
                }
    
    
    
                if ((user.LoginPassword.Equals(LoginPassword)) && (user.Role.Equals("Admin")))
    
                {
    
                    return RedirectToAction("Index", "Home");
    
    
                }
    
                if ((user.LoginPassword.Equals(LoginPassword)) && (user.Role.Equals("User")))
                {
    
                    return RedirectToAction("IndexUser", "Home");
    
    
                }
    
    
                ViewBag.InvalidPassword = "Invalid Password";
                return View(model);
    
            }
        }
    }
    

    _Layout.cshtml Page:

    <!DOCTYPE html>
    <html>
    
    <head>
        <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - Wits RMS</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body onload=display_ct();>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a href="@Url.Action("Index", "Home")">
                        <img src="~/Icons/Wits---Logo---Mono-Neg---Colloquial---Ext.png" style="height:45px; width:80px; margin-right:5px;" alt="" />
                    </a>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Researcher", "Index", "Researcher")</li>
                        <li>@Html.ActionLink("Submission", "Index", "Submission")</li>
                        <li>@Html.ActionLink("Publication", "Index", "Publication")</li>
                        <li>@Html.ActionLink("Faculty", "Index", "Faculty")</li>
                        <li>@Html.ActionLink("School", "Index", "School")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Reports", "Index", "Reports")</li>
                        <li>@Html.ActionLink("Logout", "Login", "Login")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>            
                <script type="text/javascript">
                    function display_c() {
                        var refresh = 1000; // Refresh rate in milli seconds
                        mytime = setTimeout('display_ct()', refresh)
                    }
    
                    function display_ct() {
                        var monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
                        ];
                        var dayOfWeek = ["Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
                        var strcount
                        var x = new Date()
                        var x1 = dayOfWeek [x.getDay()] + ", " + x.getDate() + " " + monthNames[x.getMonth()] + " " + x.getFullYear();
                        x1 = x1 + " " + ('0' + x.getHours()).slice(-2) + ":" + ('0' + x.getMinutes()).slice(-2) + ":" + ('0' + x.getSeconds()).slice(-2);
                        document.getElementById('ct').innerHTML = x1
                        tt = display_c();
                    }
                </script>
    
                <p>&copy; @DateTime.Now.Year - Wits RMS <span style="float:right; top:20px;" id='ct'></span></p>                             
            </footer>
        </div>
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
    

    _LayoutUser.cshtml Page:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - Wits RMS</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body onload=display_ct();>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a href="@Url.Action("IndexUser", "Home")">
                        <img src="~/Icons/Wits---Logo---Mono-Neg---Colloquial---Ext.png" style="height:45px; width:80px; margin-right:5px;" alt="" />
                    </a>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">                    
                        <li>@Html.ActionLink("Submission", "IndexUser", "Submission")</li>
                        <li>@Html.ActionLink("Publication", "Index", "Publication")</li>                    
                        <li>@Html.ActionLink("Contact", "ContactUser", "Home")</li>
                        <li>@Html.ActionLink("About", "AboutUser", "Home")</li>
                        <li>@Html.ActionLink("Logout", "Login", "Login")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <script type="text/javascript">
                    function display_c() {
                        var refresh = 1000; // Refresh rate in milli seconds
                        mytime = setTimeout('display_ct()', refresh)
                    }
    
                    function display_ct() {
                        var monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
                        ];
                        var dayOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
                        var strcount
                        var x = new Date()
                        var x1 = dayOfWeek[x.getDay()] + ", " + x.getDate() + " " + monthNames[x.getMonth()] + " " + x.getFullYear();
                        x1 = x1 + " " + ('0' + x.getHours()).slice(-2) + ":" + ('0' + x.getMinutes()).slice(-2) + ":" + ('0' + x.getSeconds()).slice(-2);
                        document.getElementById('ct').innerHTML = x1
                        tt = display_c();
                    }
                </script>
    
                <p>&copy; @DateTime.Now.Year - Wits RMS <span style="float:right; top:20px;" id='ct'></span></p>
            </footer>
        </div>
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
    
  • Kivan Ilangakoon
    Kivan Ilangakoon over 8 years
    The above code doesn't seem to work for me. I need to pull data from my Login Table in order to identify whether it is 'Admin' or 'User'. My table has an attribute titled Role, which is either 'Admin' or 'User'. and based on this I want to either pull "~/Views/Shared/_Layout.cshtml" or "~/Views/Shared/_LayoutUser.cshtml"
  • NightOwl888
    NightOwl888 about 7 years
    This example assumes you are using a security framework that is plugged into the framework, such as Identity or Membership. If using custom security, you should integrate it with ASP.NET - all that is required is to set the user in the Application_PostAuthenticateRequest method - see @luis's answer for an example.