Search Functionality in ASP.NET MVC

Chakravarthi
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 66954 red flag

This article explains how to create search functionalities in MVC

Introduction

Search plays a major role in every web application. In this article we are going to learn how to develop search functionalities in ASP.NET MVC

Simple Search


First let us learn simple search function using text box and button and display results in grid view

Note: To search records in database we must have some records in our database. To creating records and display in grid view visit : Using WebGrid to populate data as gridview in ASP.NET MVC RazorView
  
In PersonListController.cs Controller
// GET: /PersonList/

        public ViewResult Index(string q)
        {
            var persons = from p in db.People select p;
            if (!string.IsNullOrWhiteSpace(q))
            {
                persons = persons.Where(p => p.First.Contains(q));
            }
            return View(persons);
        }

In Index.cshtml View page :
@model IEnumerable<MVC_myfirst_Mvcapplication.Models.Person>

@{
    ViewBag.Title = "People List";
}

<link href="../Content/StyleSheet.css" rel="stylesheet" />
<h2>Search People</h2>
@using (Html.BeginForm("Index", "PersonList", FormMethod.Get))
{      
 <div>   
  <text>Search By FirstName : </text><input type="text" name="q"/>&nbsp;
  <input type="submit" value="Search" id="btnSubmit" />
 </div>
}

<div id ="DivGrid">
    @{
        var grid = new WebGrid(source: Model, canPage: true, rowsPerPage:4, defaultSort:"ID");
        @grid.GetHtml(tableStyle: "PGrid", headerStyle: "Header", alternatingRowStyle:"altRow", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
        grid.Column("ID"),
        grid.Column("First", "First Name"), 
        grid.Column("Last", "Last Name"),
        grid.Column("Birthdate", "Date Of Birth"), 
        grid.Column("", header: "ToEdit", format: @<text>@Html.ActionLink("Edit", "Edit", "Person", new { id = item.ID}, new { target = "_blank" })</text>)));
        }
        
</div>


Now run the project and see the simple search page (here i.e., PersonList/Index page)

 
fig: Simple Search Page

Now check is there any first name contains 'al'


fig: Search page with search result 


Custom Search

Now we are adding some additional options to the above search functionality for making search easy.
For that we need to add some radio buttons for search by type (i.e., like search by id or search by first name) 

In PersonListController.cs :

public ActionResult Persons(string q, string S)
        {
            var persons = from p in db.People select p;
            int id = Convert.ToInt32(Request["SearchType"]);
            var searchParameter = "Searching";

            if (!string.IsNullOrWhiteSpace(q))
            {
                switch (id)
                {
                    case 0:
                        int iQ = int.Parse(q);
                        persons = persons.Where(p => p.ID.Equals(iQ));
                        searchParameter += " Id for ' " + q + " '";
                        break;
                    case 1:
                        persons = persons.Where(p => p.First.Contains(q));
                        searchParameter += " First Name for ' " + q + " '";
                        break;
                    case 2:
                        persons = persons.Where(p => p.Last.Contains(q));
                        searchParameter += " Last Name for '" + q +"'";
                        break;
                }
            }
            else
            {
                searchParameter += "ALL";
            }
            ViewBag.SearchParameter = searchParameter;
            return View(persons);
        }

In Persons.cshtml View Page:

@model IEnumerable<MVC_myfirst_Mvcapplication.Models.Person>

@{
    ViewBag.Title = "People List";
}

<link href="../Content/StyleSheet.css" rel="stylesheet" />
<h2>Custom Search for People</h2>
@using (Html.BeginForm("Persons", "PersonList", FormMethod.Get, new { @class = "Search-form" }))
{
       <div id="txtBox">   
        @Html.Label("Search Persons ")
        <input type="text" name="q" />
    </div>
    <div id="radioList">
        @Html.RadioButton("SearchType", "0")
        @Html.Label("ID")
        @Html.RadioButton("SearchType", "1", true)
        @Html.Label("First Name")
        @Html.RadioButton("SearchType", "2")
        @Html.Label("Last Name")
    </div>
    <div id="btnSearch">
        <input type="submit" value="Search" id="btnSubmit" />
        </div>
}
<br />
<div id ="DivGrid">
    @{
        var grid = new WebGrid(source: Model, canPage: true, rowsPerPage:4, defaultSort:"ID");
        if(Model.Count() > 0)
        {
        <div><strong> @ViewBag.SearchParameter</strong> | @grid.TotalRowCount @Html.Label("Record(s) found")</div>
        @grid.GetHtml(tableStyle: "PGrid", headerStyle: "Header", alternatingRowStyle:"altRow", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
        grid.Column("ID"),
        grid.Column( "First", "First Name"), 
        grid.Column("Last", "Last Name"),
        grid.Column("Birthdate", "Date Of Birth")));
    }
    else{
        <hr />@Html.Label("No, Record(s) not found")<hr />
        }
        }
</div>

Now run the project and see the Cutom search page (here i.e., PersonList/Persons page)

fig: custom search

We can search people using different types like search by id or first name of last name. Now search people with the id '13', The result page is as shown bellow

fig: search people by id



Conclusion

In this article, we have learnt how to create simple and custom search functionality in MVC. Hope this article was useful.
Thanks for reading.


Page copy protected against web site content infringement by Copyscape

About the Author

Chakravarthi
Full Name: Annabattula Ashok Chakravarthi
Member Level: Starter
Member Status: Member
Member Since: 7/4/2013 11:49:03 PM
Country: India
Chakravarthi
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 5/20/2014 | Points: 25
Good article Ashok, well explained.

Thanks
Posted by: Chandradev819 on: 5/21/2014 | Points: 25
Nice article.
Posted by: Ayuagrawal29 on: 10/26/2015 | Points: 25
tried your code for searching records based on source and destination values in databse but getting all records instead of selected ones

Login to post response

Comment using Facebook(Author doesn't get notification)