MorioBoncz
MorioBoncz

Reputation: 920

Asp.Net MVC 3 Routing - Generating Outgoing URL using UrlHelper uses request RouteData

Asp.Net MVC 3, when creating outgoing link for example with UrlHelper will use RouteData from current request. I dont really understand why.

Here is my routing

routes.MapRoute("car-location", "{car}/{location}/search", 
                new {
                    controller = MVC.Home.Name,
                    action = MVC.Home.ActionNames.Search
                },
                new {
                    car = "[a-zA-Z0-9_]+",
                    location = "[a-zA-Z0-9_]+"
                });

routes.MapRoute("car-only", "{car}/search-car",
                new
                {
                    controller = MVC.Home.Name,
                    action = MVC.Home.ActionNames.Search
                },
                new
                {
                    car = "[a-zA-Z0-9_]+"
                });

Ok, now I try to generate links:

@Url.RouteUrl(new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Search, car = "SUV" })
@Url.RouteUrl(new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Search, location = "NY", car = "SUV" })

The result is correct when current URL is /SUV/search-car

and when current url is /SUV/NY/search they both turn into

So into the first link {location} is transfered from current request. I dont want my links to be changing :)

I tried putting empty location

[email protected](new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Search, car = "SUV", location = "" })

so it generates this (uses correct route but adds this as parameter)

/SUV/search-car?location=NY

Howto generate links that point to the same action and have different set of routing data and be independent of current request url.

Upvotes: 0

Views: 3780

Answers (1)

Mihai Lazar
Mihai Lazar

Reputation: 2307

Specify the Route name, car-location, or car-only as the first argument of the RouteUrl method like so

@Url.RouteUrl("car-only", new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Search, car = "SUV", location = "" })

Upvotes: 1

Related Questions