Click here to Skip to main content
15,868,340 members
Articles / Programming Languages / C#

Implementing Search Functionality in ASP.NET MVC 4

Rate me:
Please Sign up or sign in to vote.
4.56/5 (10 votes)
20 Mar 2014CPOL3 min read 112.1K   13   9
How to implement search functionality in ASP.NET MVC 4

What We are Going to cover

* In this tutorial, we are going to cover how to implement search functionality in ASP.NET MVC 4. In our web applications in MVC, we often need to add the functionality to search the database objects for specific data based on some criteria like to find employees with name starting with 'N' or to find data of employees that have Gender Male.


Creating Database For This Application

  1. First create Database

    * Open Microsoft SQL server. Click on New Query. Now execute the query below to create database.


    SQL
    Create Database searchingInmvc 

  2. Then Press F5. This will create database successfully.

Create Table and Insert Demo Data

SQL
create table tblEmployee        //creating table 
(
ID int identity primary key,
Name nvarchar(50), 
Gender nvarchar(50),
Email nvarchar(50)
) 

//Inserting Demo Data

Here, we are inserting 4 Rows in Database table:

SQL
insert into tblEmployee values('John','Female','john@geeksprogrammings.blogspot.in')
insert into tblEmployee values('funky','Male','funky@geeksprogrammings.blogspot.in')
insert into tblEmployee values('wiley','Male','wiley@geeksprogrammings.blogspot.in')
insert into tblEmployee values('ceren','Female','ceren@geeksprogrammings.blogspot.in')

Create New MVC 4 Application in Visual Studio

  1. Start Visual Studio with language selected as C#
  2. Click on File --> Then click on New Project
  3. Scroll down and select ASP.NET MVC 4 Web Application

  4. Give appropriate Name, Path and solution Name and Hit Enter
  5. Choose Empty Template
  6. Choose Razor View Engine and Hit Enter
  7. Now new MVC 4 web application is started.

Adding Models to MVC 4 Application

  1. In solution Explorer -- > Right click on Models --> Then click on New item

  2. Then select ADO.NET Entity Data Model --.> Give it a valid name like 'sampledatamodel'.
  3. Click Add:

  4. Now a dialog box appears, choose database connection to SQL Server and give your connection string a name that will be give to connection string in web.config file.

  5. Click next.
  6. Now in next dialog box, you will be presented with tables available in database table. Select your table.

  7. Now click Finish.
  8. Now Entity model of table is generated, you can rename your database here to 'Employee'.
  9. Now Model is successfully added.

Adding Controller and Views To MVC 4 Application

To add controller to database:

  1. Right click on Controllers folder in solution folder.
  2. Click on Add --> Then click on Controller:

  3. Now Add controller Dialog Box appears
  4. Give your controller a name like 'HomeController'
  5. In template, choose 'MVC controller with read/write and views using Entity Framework'
  6. The reason behind choosing this is it will automatically generate some pages to insert, delete, update data of model to which we are associating this controller
  7. Now give the Model name that we have added in previous step 'Employee'
  8. Now choose dbcontext class from dropdown menu and finally click ADD
  9. This automatically add Views for insert, update, delete and index view in views folder under controller named folder.

  10. Now run your application. This will give output below:

Adding Style And Look to Application

So we are going to search the database and retrieve data from database and then show the retrieved result to user. For this, we have to get some controls and code. The GUI design that we are going to give to this application is as below:

  1. In solution Explorer under Index view, Double click on Index.cshtml
  2. Now just before the line '<h2>Index</h2>', add a line:
    HTML
    <div style='font-family:Arial'>

    and close this div right below the code after table tag

    Other updates are in demo project. Download and use it.

  3. Update your Index.cshtml file under view folder in solution Explorer with the code in index.cshtml in uploaded file.

Code Description

In the code in attached file, we have used Razor code and instead of using <form> tag that we usually use in HTML, we have used HTML Helper below:

HTML
@using (Html.BeginForm ("Index","Home",FormMethod.Get ))
{
<b>Search by:</b>@Html.RadioButton("searchBy","Name")<text> Name</text>
@Html.RadioButton("searchBy","Gender")<text>Gender</text><br />
@Html.TextBox("Search");<input type="submit" value="Search" />
 }

In Html.BeginForm ("Index","Home",FormMethod.Get )

Here, Html.BeginForm is used in place of using form tag.

Html.BeginForm received 3 arguments:

  • Here, "Index" is Name of action that will be executed on posting form to server
  • Here, "Home" is name of controller to which this link will be redirected when clicked
  • Here, " FormMethod.Get" type of encoding method that is applied on data we are posting

Now open Controller and add code below to Index Action of home controller:

C#
if (searchby == "Gender")
{
return View(db.Employees.Where(x => x.Gender == search || search ==null).ToList());
}
else
{
return View(db.Employees.Where(x => x.Name.StartsWith(search)).ToList());
} 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionSource code should be removed (is vstudio default program) Pin
Member 1001052223-Jan-16 4:58
Member 1001052223-Jan-16 4:58 
C#
Source code should be removed (is vstudio default program)

BugMy VOte 1 Pin
Aqib Shehzad18-Oct-15 22:58
Aqib Shehzad18-Oct-15 22:58 
QuestionWhere is the full code? Pin
Member 1172392617-Jun-15 12:20
Member 1172392617-Jun-15 12:20 
QuestionThe content was copied from another website Pin
Member 1161724317-Apr-15 20:09
Member 1161724317-Apr-15 20:09 
Questionfull code Pin
Eng.Fatima M12-Feb-15 3:57
Eng.Fatima M12-Feb-15 3:57 
QuestionSearching for ID Pin
Member 102938706-May-14 3:20
Member 102938706-May-14 3:20 
AnswerRe: Searching for ID Pin
heemanshubhalla6-May-14 21:34
heemanshubhalla6-May-14 21:34 
AnswerMessage Closed Pin
11-Oct-16 0:48
Yasser Bahnasy (A)11-Oct-16 0:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.