Jason Evans
Jason Evans

Reputation: 29186

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

Upvotes: 4

Views: 2066

Answers (2)

CD..
CD..

Reputation: 74166

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
    );
}

Upvotes: 7

Neil Barnwell
Neil Barnwell

Reputation: 42165

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.

Upvotes: 1

Related Questions