简体   繁体   中英

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!

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
    {
        ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM