mvc search page example with code

MVC Searh page with pagination: It’s very easy to create a search page in asp.net but when I try to create the same in MVC I faced many problems, how to create model, how to keep searched values in search controls, pagination, I found myself nowhere, so start searching for some good examples but whatever I found was not quite helpful so try my own. I will explain the same in this article.

Here is the result we will create in this article:

alt text

First of all we will create a model, so let’s write the code for search model

using PagedList;
using System.ComponentModel.DataAnnotations;

namespace MvcSearch.Models
{
    public class ProductSearchModel
    {
        public int? Page { get; set; }
        [Display(Name="Product")]
        public string ProductName { get; set; }
        public decimal? Price { get; set; }
        public IPagedList<Product> SearchResults { get; set; }
        public string SearchButton { get; set; }
    }
}

As you can see we added two name spaces PagedList and DataAnnotations. If you have not installed PagedList with your visual studio then Install it from NuGet PagedList according to your MVC version.

There are different version of PagedList so select the correct version from list and copy the command Go to view -> Other Windows -> Package Manager Console -> paste and press enter e.g. for latest version

 PM> Install-Package PagedList.Mvc

Now time to create our controller and action method, I created a new controller Product and action method Index, here is the code

public class ProductController : Controller
{
    const int RecordsPerPage = 5;

    //I am not using httpGet or httpPost because it will be used for both
    public ActionResult Index(ProductSearchModel model)
    {
        if (!string.IsNullOrEmpty(model.SearchButton) || model.Page.HasValue)
        {
            var entities = new NorthwindEntities();
            var results = entities.Products
                .Where(p=> (p.ProductName.StartsWith(model.ProductName) 
                            || model.ProductName == null)
                && (p.Price > model.Price || model.Price == null))
                .OrderBy(p => p.ProductName);

            var pageIndex = model.Page ?? 1;
            model.SearchResults = results.ToPagedList(pageIndex, RecordsPerPage);
        }
        return View(model);
    }
}

You can change Records Per Page value, I used 5 so I can see the paging at the bottom.

And finally here is the code for our view

@model MvcSearch.Models.ProductSearchModel
@using PagedList.Mvc;

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

 @using (Html.BeginForm("Index", "Product", FormMethod.Get))
 {
    @Html.ValidationSummary(false)
    <div style="border-bottom:1px solid #bbb"><h1>Search Product</h1></div> 
    <table style="border:0px; width:500px;">
        <tr>
            <td>
                <div class="editor-label">
                    @Html.LabelFor(model => model.ProductName)
                </div>

                <div class="editor-field">
                    @Html.EditorFor(model => model.ProductName)
                    @Html.ValidationMessageFor(model => model.ProductName)
                </div>                 
            </td>
            <td>                
                <div class="editor-label">
                    @Html.LabelFor(model => model.Price)
                </div>

                <div class="editor-field">
                    @Html.EditorFor(model => model.Price)
                    @Html.ValidationMessageFor(model => model.Price)
                </div>
            </td>
            <td style="vertical-align:bottom;">                    
                <input name="SearchButton" type="submit" value="Search" />
            </td>
        </tr>
    </table>

     if (Model.SearchResults != null && Model.SearchResults.Count > 0)
     {
        <table class="table" style=" width:500px;">
            <tr>
                <th>ID</th>
                <th>Product</th>
                <th>Product Name</th>
                <th>Price</th>
                <th>Reorder Level</th>
            </tr>
         @foreach (var product in Model.SearchResults)
         {
             <tr>
                <td>@product.ProductId</td>
                <td>@product.ProductName</td>
                <td>@product.Qunatity</td>
                <td>@product.Price</td>
                <td>@product.ReorderLevel</td>
            </tr>
         }        
        </table>
        @Html.PagedListPager(Model.SearchResults, 
          page => Url.Action("Index", new RouteValueDictionary() 
          {
               { "Page", page },
               { "ProductName", Model.ProductName },
               { "Price", Model.Price }
          }),
          PagedListRenderOptions.PageNumbersOnly)
     }
 }

I used entity framework which is not needed to discuss, I hope you are expert in it, otherwise this article will be quire long.

If you are looking for a solution to search on the basis of multiple fields see MVC multiple field search with webgrid - Step 5

Download source code

Ali Adravi Having 10+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 8 years and still with the same company. Always ready to learn new technologies and tricks.
  • mvc
  • search
  • model
By Ali Adravi On 25 Aug, 13  Viewed: 21,992

Other blogs you may like

MVC insert update delete and select records

CRUD (Create, Retrieve, Update and Delete) in MVC. When we start to learn new language, first we try to run an application with “Hello World” and then CRUD functionality. So in this article we will see how to select records from database (with WebGrid, pagination and sort functionality), update a... By Ali Adravi   On 17 Aug 2013  Viewed: 70,148

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account functionality in our application then we need a thanks page after registering with our site, to say thanks for registering with us or showing confirmation that your password is successfully changed or... By Hamden   On 30 Jun 2013  Viewed: 2,148

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 4,025

Upload files with model data in MVC

Upload multiple files with model data in MVC is really very easy, when I started to test by uploading some files, I though it would be more complicated but it is really not. In my previous post [ASP.Net MVC file upload][1], I promised to post soon about how to upload multiple files. When I was... By Ali Adravi   On 04 Jun 2013  Viewed: 17,477

ASP.Net MVC file upload

How to upload file or image in asp.net mvc is not difficult but is totally different compare to asp.net FileUpload control. If we are asp.net developer and we are new to mvc then we immediately noticed we don’t have server side controls so the FileUpload control as well and our problem start here.... By Ali Adravi   On 25 May 2013  Viewed: 5,679