MVC 3: add parameters to ActionLink

I use the MVCContrib grid to output some data. When I sort the column, I get a URL that might look like this:

/?Column=ColumnName&Direction=Ascending

Suppose I want to add links to control how many results are displayed. Spontaneously, I would write something like this:

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

... which would give me:

/?PageSize=10

But I will say that I have already sorted the grid. In this case, I want to save the url parameters so that the new URL looks something like this:

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

How to do it?

+5
source share
2 answers

You can enable these other options when creating the link:

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

html-, pageSize:

Html.PaginateLink("View 10", 10)

:

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

All Articles