How to change the template (visual) of a page asp net mvc5 according to user

4

  • How would I do this using areas, and navigating through the main controllers (which are at the root of the project).

    Basically it is the following: www.algumacoisa.com/home/index = > redirect to the controller that will check the value that I searched the bank, and redirect to an area to return the view of that area (template). my biggest question is what would be the returns of these controllers.

    And if anyone has a better idea of this concept without using areas, I would be very grateful. Thanks!

        
  • asked by anonymous 30.08.2016 / 05:58

    1 answer

    4

    The secret lies in setting an ActionFilter . For example:

    public class LayoutChooserAttribute : ActionFilterAttribute
    {    
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string masterName = "_Layout";
            base.OnActionExecuted(filterContext);
            string userName = null;
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                userName = filterContext.HttpContext.User.Identity.Name;
            }
    
            // Defina masterName aqui, de acordo com sua regra de negócio
            // por usuário. Você pode chamar o banco de dados aqui, se quiser.
    
            var result = filterContext.Result as ViewResult;
            if (result != null)
            {
                result.MasterName = masterName;
            }
        }
    }
    

    Usage:

    Can be by Controller :

    [LayoutChooser]
    public class MeuController : Controller { ... }
    

    Or register as global filter ( Global.asax.cs ):

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        GlobalFilters.Filters.Add(new LayoutChooserAttribute());
    
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        ...
    }
    
        
    30.08.2016 / 06:11