Routing advanced parameters with dashes in MVC

I made a routing definition as follows:

 routes.MapRoute("ProductSearch", "Search-{MainGroup}-{SubGroup}-{ItemType}",
   new {
    controller = "Product",
    action = "Search",
    MainGroup = "", SubGroup = "", ItemWebType = ""});

It does not work if the parameters are empty. In fact, it resolves the URL, so the Url.Action method resolves the path "Search-12--", but the link does not work, so the GET of the page does not work.

Using slashes, the Url.Action method does "Search / 12"

"Search/{MainGroup}/{SubGroup}/{ItemType}"

Can this be fixed?

I made a sample with the mvc project by default: Added: before the default route:

    routes.MapRoute(DefaultSearch", "Search-{MainGroup}-{Subgroup}-{ItemType}",
        new {controller = "Home",action = "About", MainGroup = "", 
              Subgroup = "", ItemType = ""});

in Home / index.aspx:

<a href="<%=Url.Action("About", "Home", new {maingroup = "2", subgroup = "", itemType = ""}) %>">
    Search</a>

In HomeController:

public ActionResult About(string maingroup, string subgroup, string itemtype)
{
  return View();
}

Click the link and 404

+3
source share
1 answer

Which version are you using? in mvc 2 you can use UrlParameter.Optionalas default values ​​for routes.

+1
source

Source: https://habr.com/ru/post/1746367/


All Articles