How to use pagedlistpager when passing a viewmodel to my action
What am I using for my second parameter in '@ Html.PagedListPager'? If I have an action in my controller that takes a view model like this
[HttpPost]
[AllowAnonymous]
public ActionResult Search(HomePageViewModel viewModel)
{
var pagedList = repository.GetYogaList(viewModel.SearchQuery, viewmodel.Date)
viewModel.YogaList = pagedList;
if (Request.IsAjaxRequest())
{
return PartialView("_mySpaces", viewModel);
}
return View(viewModel);
}
and a partial page containing a list of html hpml pages paged out by page
here is the partial "_mySpaces.html"
@model HomePageViewModel
<div id="yogaSpaceList">
<div class="pagedList">
@Html.PagedListPager(Model.YogaSpaces, page => Url.Action("Search", new { Model }), PagedListRenderOptions.MinimalWithItemCountText)
</div>
@foreach (var space in Model.YogaSpaces) {
<div>
<h4>@space.Overview.Title</h4>
<div>
@space.Overview.Summary
</div>
</div>
}
</div>
source to share
Ok, you can pass the viewmodel back to the action, but as before, it must be a GET method, so mark your action with the HttpGet attribute. The MVC framework will broadcast / bind the query string to your view model.
Your controller should look something like this:
[HttpGet]
public ActionResult Search(ViewModel viewModel)
{
\\ do something useful here and return ActionResult .....
}
You will need to add a page property to your ViewModel and the method allows your .cshtml code to set the page number and returns the viewmodel as an object. MVC converts the object to a query string for an action reference.
Public class ViewModel {
// other properties and stuff
public int? Page { get; set; }
public object ToPagedListParameters(int page)
{
this.Page = page;
return this;
}
}
Then all it takes is a small tweak to your .cshtml file
<div class="pagedList">
@Html.PagedListPager(viewModel, page => Url.Action("Search",viewModel.ToPagedListParameters(page))
</div>
Note. I only have working with simple viewModels and haven't tried this with viewModels that contain collections or lists.
source to share