Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter value not passed in ASP.NET MVC route

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().

like image 326
Jason Evans Avatar asked Feb 25 '23 07:02

Jason Evans


2 Answers

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
    );
}
like image 54
CD.. Avatar answered Mar 06 '23 17:03

CD..


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.

like image 40
Neil Barnwell Avatar answered Mar 06 '23 17:03

Neil Barnwell