ASP .NET MVC 5 - 使用子文件夹时的URL路由

时间:2017-09-19 08:29:18

标签: asp.net-mvc routing

我有以下目录结构,其中一些控制器位于子目录中:

 Controllers
     |
     |__Homecontroller.cs  
     |
     |__Accounts
     |  |
     |  |__PayableController.cs
     |
     |__Sales
        |
        |__ElectronicsController.cs

我的观点有以下结构:

 Views
    |
    |__Accounts
    |  |
    |  |__Payable
    |     |
    |     |__Create.cshtml
    |     |__Detail.cshtml
    |     |__Edit.cshtml
    |     |__Index.cshtml
    |
    |__Home
    |  |
    |  |__Index.cshtml
    |
    |__Sales
       |
       |__Electronics
          |
          |__Create.cshtml
          |__Detail.cshtml
          |__Edit.cshtml
          |__Index.cshtml

如何添加路线,以便在用户导航到例如mysite/accounts/payable/create返回正确的视图?

以下控制器和路由无效?

namespace MySite.Controllers.Accounts
{
  public class PayableController : Controller
  {
        public ActionResult Index(int? page)
        {
            // DO some stuff

            return View(viewModel);
        }

  }
}

routes.MapRoute(
            name: "Department",
            url: "{department}/{controller}/{action}/{id}",
            defaults: new {controller = "", action = "", id = UrlParameter.Optional}
        );

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

1 个答案:

答案 0 :(得分:0)

我也有这个问题,当我为所有控制器使用相同的命名空间时,它对我有效。

在你的情况下,即使控制器文件是任何子文件夹,也尝试使用相同的命名空间MySite.Controllers。