Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - Switch View based on User Role

Tags:

c#

asp.net-mvc

I have a requirement in my MVC application to present the user with a different view of an action based on their role. What is the best way to do this?

Currently I have the following code which I do not like:

if (HttpContext.User.IsInRole("Admin"))
    return View("Details.Admin", model);
else if (HttpContext.User.IsInRole("Power"))
    return View("Details.Power", model);

//default
return View("Details", model);

Would this be a good fit for an Action Filter?

like image 288
Dismissile Avatar asked Mar 23 '12 15:03

Dismissile


1 Answers

Would this be a good fit for an Action Filter?

Absolutely:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var result = filterContext.Result as ViewResultBase;
        if (result != null)
        {
            var user = filterContext.HttpContext.User;
            if (user.IsInRole("Admin"))
            {
                result.ViewName = string.Format("{0}.Admin", filterContext.ActionDescriptor.ActionName);
            }
            else if (user.IsInRole("Power"))
            {
                result.ViewName = string.Format("{0}.Power", filterContext.ActionDescriptor.ActionName);
            }
        }
    }
}

Or you could even build a custom view engine.

like image 188
Darin Dimitrov Avatar answered Nov 10 '22 22:11

Darin Dimitrov