Asp.net MVC Routelink null controller parameter

453 Views Asked by At

I have two routes, the default one

  routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

I added another route, sometimes the parameter will by a string

            routes.MapRoute(
            name: "ByName",
            url: "{controller}/{action}/{name}",
            defaults: new { controller = "Home", action = "Index", name = UrlParameter.Optional }
        );

When I use the "ByName" route in a RouteLink, the URL is fine, but the parameter in my controller is empty

In the view:

@Html.RouteLink(application.Nom, "ByName", new {controller= "Packaging", action = "EditApplication", name = application.Nom})

The controller

public ActionResult EditApplication(string name)

URL result is fine: .../Packaging/EditApplication/VisualStudio, but the parameter value stays null. Why?

Thank you

1

There are 1 best solutions below

1
On BEST ANSWER

You cannot have TWO Routes with same parameters and same definition, first one will take precedence. Instead, you need to have something like shown below with specific constraints in routes.

 routes.MapRoute(
        name: "ByName",
        url: "sample/{action}/{name}",
        defaults: new { controller = "Home", action = "Index", name = UrlParameter.Optional }
        );

 routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );