MVC 3: Append get parameters on a ActionLink
Asked Answered
B

2

5

I'm using the MVCContrib grid to output some data. When I sort a column, I get a url which may look like this:

/?Column=ColumnName&Direction=Ascending

Lets say I want to add links to control how many results are being shown. Spontaneously I would write something like this:

Html.ActionLink("View 10", "Index", new { pageSize = 10 })

... which would give me:

/?PageSize=10

But say I already sorted the grid. In that case I want to save the url parameters, making the new url look something like this:

/?Column=ColumnName&Direction=Ascending&PageSize=10

How can accomplish this?

Basilisk answered 11/8, 2011 at 10:27 Comment(0)
H
9

You could include those other parameters when generating the link:

Html.ActionLink(
    "View 10", 
    "Index", 
    new {
        Column = Request["Column"],
        Direction = Request["Direction"],
        pageSize = 10 
    }
)

or write a custom html helper which will automatically include all current query string parameters and append the pageSize parameter:

Html.PaginateLink("View 10", 10)

and here's how the helper could look like:

public static class HtmlExtensions
{
    public static MvcHtmlString PaginateLink(
        this HtmlHelper helper, 
        string linkText, 
        int pageSize
    )
    {
        var query = helper.ViewContext.HttpContext.Request.QueryString;
        var values = query.AllKeys.ToDictionary(key => key, key => (object)query[key]);
        values["pageSize"] = pageSize;
        var routeValues = new RouteValueDictionary(values);
        return helper.ActionLink(linkText, "Index", routeValues);
    }
}
Heydon answered 11/8, 2011 at 11:58 Comment(3)
That would work in this specific case, but I was thinking of a more dynamic solution.Basilisk
@Bridget the Midget, then a custom HTML helper is the way to go.Heydon
@Bridget the Midget, I have updated my answer to include an example of how the custom HTML helper might look like.Heydon
B
2

You can also use solution from question ASP.NET MVC: The right way to propagate query parameter through all ActionLinks. It will allow you to preserve any parameters on any routes you like.

Beckibeckie answered 1/3, 2012 at 13:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.