How to use areas only using root controller

Asked

Viewed 54 times

1

I created an ASP.NET MVC 5 project where I had done one template, so now we’re going to have several templates divided by areas. Only that the controllers will be the same, so I didn’t want to create the same controllers for all the areas. How do I do it?

 //exemplo link html 
     <a href='/home/index'> Home </a>

//controller:
    public ActionResult Index(){
        //aqui faço a verificação que retornará a area

        string retorno = obterAreaUtilizada(); //ex.:"template02"

        return RedirectToAction("Index","Home", new { area = retorno });
    }

Only I’m testing here and it’s making a mistake, by just not using controller in the areas... someone could help me?

EDIT

I’ve found a way, but I need to know if she’s coherent, not a gambit:

    public ActionResult Index(){
        //aqui faço a verificação que retornará a area

        string retorno = obterAreaUtilizada(); //ex.:"template02"

        string caminho = string.format("~/areas/{0}/views/home/index.cshtml",retorno);
        return View(caminho);
    }

Please, if anyone knows a more suitable solution, it would be great if they shared it. Thank you very much.

1 answer

1


I’ve found a way, but I need to know if she’s coherent, not a gambit.

It’s a scam. You’re actually doing the Controller have to interpret the route getting the requested area by request, which is wrong. The role of the Controller not interpreting routes, but processing a request made for a given route.

The correct way to do this is by registering your Controller in a namespace common to all routes. For example:

namespace MeuProjeto.Controllers.AreasComum
{
    public class MeuControllerDeArea : Controller { ... }
}

When creating an area, a file called NomeDaAreaAreaRegistration.cs that records a route to that area. Just complete the parameterization of the route of this file as follows:

namespace MeuProjeto.Areas.MinhaArea
{
    public class MinhaAreaAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "MinhaArea";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                name: "MinhaArea_default",
                url: "MinhaArea/{controller}/{action}/{id}",
                defaults: new { controller = "MeuControllerDeArea", action = "Index", id = UrlParameter.Optional },
                namespaces: new string[] { "MeuProjeto.Controllers.AreasComum" }
            );
        }
    }
}

Write your Controllers normally, only by creating the respective Views in the directories expected from each Controller inside the directory Views of each of its Areas.

Create how many Areas deem necessary by repeating the route registration process for each Area.

Heed: If there are two Controllers with the same name in namespaces different routes can be lost. If this occurs, it is necessary to explain to ASP.NET MVC what the namespace standard for searching for Controllers, as follows:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        // Insira a linha abaixo com o namespace padrão dos seu Controllers que não pertencem a Areas
        ControllerBuilder.Current.DefaultNamespaces.Add("MeuProjeto.Controllers");
    }
    ...
}
  • Thank you very much for the reply Gypsy, I have a doubt, how would the url look like this way? why the idea is to do type www.algumacoisa.com/home/index and through the controller I redirect to my view. if I do what you said by entering this url as it would be the return of the controller?

  • or would use the first code block with redirectToView?

  • www.algumacoisa.com/home/index does not enter any area. Entering area would be something like www.algumacoisa.com/area/home/index. The return is almost the same as the Controllers but in an isolated context Controllers normal.

  • So the way you explained I would have to use the .../myArea/... to access it?

  • Exactly. That’s what the areas are for.

  • redirectToAction would be a good option to make use of areas without making it explicit in the url? as I said is a visual change where areas are just views and js of them, some even as shortcut for being the same views.

  • Areas are not resources for changing templates. RedirectToAction is a function used both by Controllers of Areas as Controllers root. You are trying to use Areas in a wrong way. I suggest asking another question being more specific than what you want is a change of templates in accordance with specific criteria.

  • 1

    Oh yes, thank you very much Gypsy. I will mark your explanation as an answer because I understood better about it. Thanks !

  • @cigano_morrison_mendez cigano, I asked another more specific question, http://answall.com/questions/149864/como-trocar-o-templatevisual-de-uma-pagina-asp-net-mvc5-de-acordo-usu%C3%A1rio

Show 4 more comments

Browser other questions tagged

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