开发者

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

开发者 https://www.devze.com 2023-03-11 15:40 出处:网络
Asp.Net MVC 3, when creating outgoing link for example with UrlHelper will use RouteData from current request. I dont really understand why.

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-l开发者_C百科ocation", "{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

  • /SUV/search-car
  • /SUV/NY/search

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

  • /SUV/NY/search
  • /SUV/NY/search

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

I tried putting empty location

$@Url.RouteUrl(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.


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 = "" })
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号