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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With