Asp.Net 默认 ID 的 MVC 路由问题



我有一个 Asp.Net Mvc网站,它有一个列表控制器。路线如下所示:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new string[] { "MySite.Web.Controllers" }
);

相当标准。现在,我的列表控制器中有许多控制器操作。我希望能够转到/listing/84 并让它转到索引操作或/listing/create、/listing/edit、/listing/favorite 或/listing/other 并让它转到相应的操作。对于我的大多数路线,情况已经如此。这是我的控制器代码:

public ActionResult Index(long? id)
{
    // my code that never gets hit
}

我错过了什么吗?

您可以为此定义特定路由和 id 约束:

routes.MapRoute(
    "ActionLess",
    "{controller}/{id}",
    new { controller = "Home", action = "Index" },
    new { id = @"^[0-9]+$" },
    new string[] { "MySite.Web.Controllers" }
);
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new string[] { "MySite.Web.Controllers" }
);
您可以

为其创建两条新路由

对于 lisitng/创建 用于导航创建操作

routes.MapRoute(
     "listingCreate", // Route name
     "listing/Create", // URL with parameters
      new { controller = "listing", action = "Create" } 
);

对于传递 ID 时的索引操作

routes.MapRoute(
     "lisingid", // Route name
     "listing/{Id}", // URL with parameters
      new { controller = "listing", action = "Index", id = UrlParameter.Optional } 
);

我希望,它会帮助你。

最新更新