Parameter value not passed in the ASP.NET MVC path

I am learning how to create custom routes in ASP.NET MVC and hit a brick wall. In my Global.asax.cs file, I added the following:

public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); // My Custom Route. routes.MapRoute( "User_Filter", "home/filter/{name}", new { controller = "Home", action = "Filter", name = String.Empty } ); } 

The idea is that I can go to http://localhost:123/home/filter/mynameparam . Here is my controller:

 public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Filter(string name) { return this.Content(String.Format("You found me {0}", name)); } } 

When I go to http://localhost:123/home/filter/mynameparam , the contoller Filter method is called, but the name parameter is always null .

Can someone point to the correct way to create my custom route so that it passes part of the name in the URL to the name parameter for Filter() .

+4
source share
2 answers

The Default route should be the last. Try it like this:

 public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // My Custom Route. routes.MapRoute( "User_Filter", "home/filter/{name}", new { controller = "Home", action = "Filter", name = String.Empty } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } 
+7
source

I believe your routes should be the other way around?

Routes are processed in order, so if the first (default, OOTB) route matches the URL, then the one that will be used.

+1
source

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


All Articles