I have set up a webgrid and it seems to work fine, allowing me to sort and page. I have added a filter option which also works well however if I filter and then sort the results, the filter is lost and all records are displayed.
Here is my Razor view code:
@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "Get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "myGrid" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Document Search</legend>
<div class="editor-label">
@Html.Label("Enter a Document code:")
</div>
<div class="editor-field">
@Html.Editor("search")
</div>
<p>
<input type="submit" value="Search" />
</p>
</fieldset>
}
@{
WebGrid grid = new WebGrid(null, rowsPerPage: 10, canPage: true, canSort: true, ajaxUpdateContainerId: "myGrid");
grid.Bind(Model, autoSortAndPage: true);
}
<div id="myGrid">
@grid.GetHtml(mode: WebGridPagerModes.All, firstText: "First Page", nextText: "Next", previousText: "Previous", lastText: "Last Page", numericLinksCount: 10,
columns: grid.Columns(
grid.Column("DocumentID", "Document Code", canSort: true),
grid.Column("Title", "Document Title", canSort: true)
)
)
</div>
And here is my action:
public ActionResult Index(string search)
{
List<DocumentIndexViewModel> viewModel = Mapper.Map<List<DocumentIndexViewModel>>(DocumentService.GetDocumentsBySearch(search));
if (Request.IsAjaxRequest())
return PartialView("_IndexGrid", viewModel);
else
return View(viewModel);
}
How do I maintain the filter when I sort the displayed records? It seems like I need to append the search string onto the sort links somehow but am not sure how to proceed.
Since you are using GET for the filter this should preserve it. I am unable to reproduce the problem. Here’s my full working test case.
Model:
Controller:
Main view (
~/Views/Home/Index.cshtml):~/Views/Home/_IndexGrid.cshtmlpartial:Sorting and pagination preserves the search filter that was entered because it was in the query string.