How to change the template(visual) of an Asp net mvc5 page according to user

Asked

Viewed 356 times

5

Here’s the thing, I need to read a property that returns me 1,2,3... and with it I determine what kind of visual the page will have, template01,template02...

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

Basically it is as follows: www.algumacoisa.com/home/index => redirect to the controller that will verify the value I searched in the bank, and redirect to an area to return the view of that area(template). my biggest doubt is how would the returns of these controllers.

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

1 answer

5


The secret lies in the definition of a 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;
        }
    }
}

Use:

It may be by Controller:

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

Or registration as a global filter (Global.asax.cs):

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    GlobalFilters.Filters.Add(new LayoutChooserAttribute());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    ...
}
  • 1

    Old card, so I can make my rule to define the template and still make the query in the own superscript.. thanks gypsy ! I will study this concept well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.