1

I 3 Routen in RouteConfig haben:Asp.net MVC 5 MapRoute für mehrere Routen

routes.MapRoute(
    name: "ByGroupName", 
    url: "catalog/{categoryname}/{groupname}", 
    defaults: new { controller = "Catalog", action = "Catalog" } 
); 
routes.MapRoute(
    name: "ByCatName", 
    url: "catalog/{categoryname}", 
    defaults: new { controller = "Catalog", action = "Catalog" } 
); 
routes.MapRoute(
    name: "ByBrandId", 
    url: "catalog/brand/{brandId}", 
    defaults: new { controller = "Catalog", action = "Catalog" } 
); 

und dies ist mein Regler Empfangsparameter:

public ActionResult Catalog(
    string categoryName = null, 
    string groupName = null, 
    int pageNumber = 1, 
    int orderBy = 5, 
    int pageSize = 20, 
    int brandId = 0, 
    bool bundle = false, 
    bool outlet = false, 
    string query_r = null) 
{ 
// ... 
} 

, wenn ich im Hinblick auf eine Verknüpfung Verwendung mit @Url.RouteUrl("ByBrandId", new {brandId = 5}), erhalte ich in Aktion einen Parameter "Kategoriename" = "Marke" und brandid = 0 statt nur von brandid = 5 ...

Als ich "http://localhost:3453/catalog/brand/5" mit "ByBrandId" RouteUrl Rufen ich möchte zu erhalten brandid = 5 in Action ..., um das Äquivalent von "http://localhost:3453/catalog/Catalog?brandId=1"

dank

Antwort

1

Ihr Routing falsch konfiguriert ist. Wenn Sie die URL /Catalog/brand/something übergeben, wird immer die Route ByGroupName anstelle der vorgesehenen Route ByBrandId passen.

Zuerst sollten Sie die Bestellung korrigieren. Aber auch die ersten zwei Strecken sind genau die gleichen mit Ausnahme der optionalen Gruppenname, so können Sie vereinfachen zu:

routes.MapRoute(
    name: "ByBrandId", 
    url: "catalog/brand/{brandId}", 
    defaults: new { controller = "Catalog", action = "Catalog" } 
); 
routes.MapRoute(
    name: "ByGroupName", 
    url: "catalog/{categoryname}/{groupname}", 
    defaults: new { controller = "Catalog", action = "Catalog", groupname = UrlParameter.Optional } 
); 

Wenn Sie jetzt @Url.RouteUrl("ByBrandId", new {brandId = 5}) verwenden es sollte Ihnen die erwartete Ausgabe /catalog/brand/5.

Eine vollständige Erklärung finden Sie unter Why map special routes first before common routes in asp.net mvc.