Stas Petrov Stas Petrov - 2 months ago 5
ASP.NET (C#) Question

ASP.NET MVC two controllers with same name, how to specify view location

I have two controllers with same name in different namespaces

-Controllers
--AdminCp
---AccountController.cs
--Cp
---AccountrController.cs


And same view location structure

-Views
--AdminCp
---Account
----Login.cshtml
--Cp
---Account
----Login.cshtml


My Account controllers contains method Login

public ActionResult Login()
{
return View();
}


I also have custom
RazorViewEngine


public ExtendedRazorViewEngine()
{
ViewLocationFormats = new[]
{
"~/Views/AdminCp/{1}/{0}.cshtml",
"~/Views/Cp/{1}/{0}.cshtml",
"~/Views/{1}/{0}.cshtml",
"~/Views/Layout/{0}.cshtml",
};
}


My routing uses
MvcCodeRouting


routes.MapCodeRoutes(typeof (Controllers.HomeController));


But when i trying route to the action
Login
in
Cp namespace
i am getting view from
AdminCp namesapce


http://example.com/cp/account/login ---> /views/admincp/account/login.cshtml


I know that i can pass path locatin in
View()
But... It looks ugly.

Can somebody help me with this? Thanks in advance!

Answer

You need to have Areas to implement such function.A good link to start is :

Areas

Also,you need to change your RouteConfig:

context.MapRoute(
    "Default",
    "{area}/{controller}/{action}/{id}",
    new { area = "MyOneWay", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Furtermore,ypou can have your controller in below defined way:

namespace MyApp.Areas.MyOneWay.Controllers
{
    public class HomeController : Controller
    {
        ...
    }
}

namespace MyApp.Areas.MySecondWay.Controllers
{
    public class HomeController : Controller
    {
        ...
    }
}
Comments