BenoitM
BenoitM

Reputation: 97

Asp.net MVC Routelink null controller parameter

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

Upvotes: 0

Views: 433

Answers (1)

ramiramilu
ramiramilu

Reputation: 17182

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

Upvotes: 1

Related Questions