Create an ActionLink / RouteLink from a Paging UserControl that uses the current route values ​​and modelstate

I am implementing a site that has a search that can be performed using controller methods that are accessible from two different routes. One is dependent on the default route (using Post data or query string values ​​for search parameters), and one is an SEO optimization URL that takes location and phrase through two route values. The second route is as follows:

routes.MapRoute("SEOSearch", "Search/{seoLocation}/{seoSearchString}",
  new { controller = "Search", 
        action = "SEOResults", 
        seoLocation = (string)null, 
        seoSearchString = (string)null });

You might be wondering why I have two different routes - because the search offers many other options than just the location and the phrase - but I want SEO'd URLs to include these two paths rather than using the query string.

As I said, the first route is the default route /controller/action/id, and the correct controller / action for it is “Search” and “Index”.

In the end, both actions perform the same search operation in the controller, and both of them will display the results using the Index view, since their result models are identical.

In the index view, I use a partial view for search terms, another partial for results, and another for search call.

The problem I am facing is forcing the paging element to display the correct link to start the current search for the next page using the same URL format as the current request.

What I want

So, if you switched to /Search?Location=[location]&Phrase=[phrase], I want the link generated by the pager to be /Search?Location=[location]&Phrase=[phrase]&Page=2.

, /Search/[location]/[phrase], /Search/[location]/[phrase]?Page=2.

, , :

<%=  Html.RouteLink("Previous Page", 
       RouteHelpers.Combine(ViewContext.RouteData.Values, 
       new RouteValueDictionary() { { "Page", Model.Results.PageNo + 1}})) %>

RouteHelpers.Combine - , , RouteValueDictionary. RouteValues ​​ , Action ( , ), ModelState, , , .. , Url /Search/London/Widgets, /Search/London/Widgets?PageSize=50, PageSize .

, -SEO-, .. /Search?Location=London&Phrase=Widgets, URL- /Search?Page=x.

, , , , URL-, ( ), URL- .

, !? , MVC !

+3
1

RouteHelper . , ActionLink. . :

RouteValueDictionary values = RouteValuesHelpers.MergeRouteValues(
    actionName,
    controllerName,
    requestContext.RouteData.Values,
    routeValues,
    includeImplicitMvcValues); // true for ActionLink; false for RouteLink

routeValues - . requestContext.RouteData.Values.

, :

Html.ActionLink(
    "whatever",
    this.ViewContext.RouteData.Values["action"],
    this.ViewContext.RouteData.Values["controller"],
    new { Page = /* whatever needs to be */ },
    null)

, HTML.

, , , /Search/SeoLocation/SeoSearchString - , SeoLocation SeoSearchString id.

. , , .

+3

Source: https://habr.com/ru/post/1736492/


All Articles