Dismissile
Dismissile

Reputation: 33071

MVC - Switch View based on User Role

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?

Upvotes: 5

Views: 2243

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 6

Related Questions