I'm learning about creating custom routes in ASP.NET MVC and have hit a brick wall. In my Global.asax.cs file, I've 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 for me to able to navigate 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 navigate to http://localhost:123/home/filter/mynameparam
the contoller method Filter
is called, but the parameter name
is always null
.
Could someone give a pointer as to the correct way for me to build my custom route, so that it passes the name part in the url into the name
parameter for Filter()
.
The Default
route should be the last one.
Try it this way:
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
);
}
I believe your routes need to be the other way round?
The routes are processed in order, so if the first (default, OOTB) route matches the URL, that's the one that'll be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With