Ehsan
Ehsan

Reputation: 834

Render different views for different roles just by one action in asp.net mvc

Suppose a web application which has three part or so-called three access level:

  1. One for every visitor (just for seeing the content and no need for authentication)
  2. One for Users (Authorized for users)
  3. One for the Administrator (authorized for admin)

now, administrator has access for every content and every operation in the system and Users could do some operations. I don't wanna to create separate areas for Users and Administrator because I don't want to repeat the same code in every area. for example both admin and user can create product, see the list of products, create catalog and... and also every visitor can also sees the list of product, blog posts, ... So it's not a good idea to separate and make the code duplicated just for separating the tasks. I haven't created any area and I want to control the authentication and authorization by defining the user role when he/she is in the system(ideas!?) but the main issue comes when I want to have separate user interface (views) for users and admin. as I want to use just one Controller for products, Catalog, ... and set authentication and authorization for them, how can I render different view for every request by admin and user? I also don't want to make my code dirty by putting bunch of if/else to define which view to render (I'd rather to duplicate the code in areas!), any solution?

Upvotes: 1

Views: 2584

Answers (1)

Erik Philips
Erik Philips

Reputation: 54636

Probably the easiest solution is to write your own RazorViewEngine(Assuming you are using razor).

Then when you want to retrieve a view for a user, you can check the user role and assign the view you want. This is a basic and crude example:

public override ViewEngineResult FindPartialView(
  ControllerContext controllerContext, 
  string partialViewName, 
  bool useCache)
{
  if (controllerContext.User.IsInRole("Admin"))
  {
    var adminViewLocations = new string[] {"~/AdminViews/" }
    return new ViewEngineResult(adminViewLocations);
  }
  return base.FindPartialView(controllerContext, partialViewName, useCache);
}

Doing this means that all users use the same controllers and authentication, but the views change based on roles (or whatever you want).

You can read more about A Custom View Engine with Dynamic View Location.

Upvotes: 4

Related Questions