//ViewModel
using PagedList;
namespace SearchFormResultPagingExample.Models {
public class SearchViewModel {
public int? Page { get; set; }
public string EmailAddress { get; set; }
public string LastName { get; set; }
public IPagedListSearchResults { get; set; }
public string SearchButton { get; set; }
}
}
using System.Linq;
using System.Web.Mvc;
using SearchFormResultPagingExample.Models;
using PagedList; //NOTE: use Nuget to reference PagedList
namespace SearchFormResultPagingExample.Controllers {
public class SearchController : Controller {
const int RecordsPerPage = 25;
public ActionResult Index(SearchViewModel model) {
if (!string.IsNullOrEmpty(model.SearchButton) || model.Page.HasValue) {
var entities = new AdventureWorksEntities();
var results = entities.Contacts.Where(c => c.LastName.StartsWith(model.LastName) && c.EmailAddress.StartsWith(model.EmailAddress))
.OrderBy(o => o.LastName);
var pageIndex = model.Page ?? 0;
model.SearchResults = results.ToPagedList(pageIndex, 25);
}
return View(model);
}
}
}
//View
@model SearchFormResultPagingExample.Models.SearchViewModel
@using PagedList.Mvc;
@using (Html.BeginForm("Index", "Search", FormMethod.Get)) {
@Html.ValidationSummary(false)
<fieldset>
<legend>Contact Searchlegend>
<div class="editor-label">
@Html.LabelFor(model => model.EmailAddress)
div>
<div class="editor-field">
@Html.EditorFor(model => model.EmailAddress)
@Html.ValidationMessageFor(model => model.EmailAddress)
div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
div>
<p>
<input name="SearchButton" type="submit" value="Search" />
p>
fieldset>
}
@if (Model.SearchResults != null && Model.SearchResults.Count > 0) {
foreach (var result in Model.SearchResults) {
<hr />
<table >
<tr>
<td valign="top" >
<div >@result.LastName, @result.FirstNamediv>
@result.Title<br />
@result.Phone<br />
@result.EmailAddress
<td>
<tr>
<table>
}
<hr />
@Html.PagedListPager(Model.SearchResults,
page => Url.Action("Index", new RouteValueDictionary() {
{ "Page", page },
{ "EmailAddress", Model.EmailAddress },
{ "LastName", Model.LastName }
}),
PagedListRenderOptions.PageNumbersOnly)
}