How to Set Layout Page by User Role in Asp.Net Core MVC Using C#.net

How to dynamically set or assign layout page of a view as per user role in asp.net core 8 mvc application using c#.net. Bind user role in dropdown.
In today's article I will show a simple tutorial with an example that ho you can set a layout page to a view as per the user role in asp.net core 8 mvc application using c#.net. So, for this article first we will create a new asp.net core 8 mvc application and add two different layout pages. Now let's create two different layout pages.  


In above image I have taken two layout pages one for "Admin" and "Employee". This we will load as per selected role in dropdown list. Let's add some code to both the views which will have help us to identify the difference between both layout after load.
_Admin.cshtml
 <!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
     <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
     <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
     <link rel="stylesheet" href="~/Project.styles.css" asp-append-version="true" />
</head>
<body>
    <h1>Admin Layout</h1>
    <div>
        @RenderBody()
    </div>
</body>
</html> 
_Employee.cshtml
 <!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
     <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
     <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
     <link rel="stylesheet" href="~/Project.styles.css" asp-append-version="true" />
</head>
<body>
    <h1>Employee Layout</h1>
    <div>
        @RenderBody()
    </div>
</body>
</html>
Now let's add a model class file as shown below. Here we will define soe properties which we will use in our Controller and View.
public class UserModel
{
    public int RoleId { get; set; }
    public List<RoleModel> Roles { get; set; }
}
public class RoleModel
{
    public int Id { get; set; }
    public string RoleName { get; set; }
} 
In above model class file i have defined two model class. First model represent the user model and second model class represent the user role model. Here in user model i have taken the list of the RoleModel class. This will help us to bind the dropdown list with the help Html.DropDownListFor. One of the integer property named as RoleId will used to provide the selected value at the controller end. Now let's add a controller and add the HttpGet Index method. 
[HttpGet]
public IActionResult Index()
{
    UserModel userModel = new UserModel();
    userModel.Roles = new List<RoleModel>() {
    new RoleModel { Id = 0, RoleName = "Select Role" },
    new RoleModel { Id = 1, RoleName = "Admin" },
    new RoleModel { Id = 2, RoleName = "Employee" }};
    return View(userModel);
}
 
 In above code I have used HttpGet named as Index and its return type is IActionResult.  This will act as page load.  Here I have added some roles to the dropdown list. This we will bind to dropdown in our view. Now let's create a View and add the below code in it.
 @model UserModel
@{
	ViewData["Title"] = "Home Page";
	switch (Model.RoleId)
	{
		case 1:
			Layout = "_Admin";
			break;
		case 2:
			Layout = "_Employee";
			break;
		default:
			Layout = "_Layout";
			break;
	}
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
	<div class="text-left" style="width:200px;">
		<h3>
			Role Based Test
		</h3>
		<br />Role:
		@Html.DropDownListFor(m => m.RoleId, new SelectList(Model.Roles, "Id", "RoleName"), new { @class = "form-select" })
		<br />
		<input type="submit" value="Submit" />

	</div>
} 
In above view code first check the switch statement. Here I have check what the role id and on the bases of role id the layout have been loaded to the page, or we are assigning the layout page to the view. Here is role id is "0" at that time the default layout will be loaded. If it is 1 load the admin layout and if the role id is 2 on that case assign the employee layout to the view. 

After defining the dynamic layout allocation, I have defined the form tag. This will help us to get the user selected at controller end. In next line I have bind the dropdown list and at last I have used submit button the post the page to the controller where we will capture the user selected role and again pass it to view to load the layout page as per role. Now in last let's create the HttpPost method in controller. 
[HttpPost]
public IActionResult Index(UserModel userModel)
{
    userModel.Roles = new List<RoleModel>() {
    new RoleModel { Id = 0, RoleName = "Select Role" },
    new RoleModel { Id = 1, RoleName = "Admin" },
    new RoleModel { Id = 2, RoleName = "Employee" }};
    return View(userModel);
} 
In above code I have written the HttpPost method in controller. Here I have passed the user model as a parameter and in next line I have again reassign the value to the dropdown. We are resigning the value because we know that in mvc control does not maintain the state of the controls.  Now we have done let's run the code to check the output.

Dropdown in View with role dropdown
In above we are able to get the dropdown and the submit button. Now let's expand the dropdown and check for the roles in dropdown.

Dropdown with role
Now select a role let's say admin and click on submit button. Before submitting the button, I have placed a break point in controller httppost methos and in the view. Now let's check the code. 
Controller Value

In above code you can see we are having the RoleId value as 1. Now proceed to next step and check the break point on View.
 
Layout Selection in View

Here you can see break point is moving the _Admin layout. This will load the admin layout. Now press F5 to check the output.


Here we can see we are getting admin layout loaded. Now let's check same for Employee.

Employee Layout

Post a Comment