What we are Going To cover
* In this Tutrial 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 creteria like to find employees with name starting with 'N' or to find data of employees that have Gender Male
Download Demo App With Database Link Below
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
Create Database searchingInmvc
Create Database Searching in Asp.net MVC 4 |
2. Then Press F5 . This will create Database successfully
Create Table And Inserting Demo Data
create table tblEmployee //creating table
(
ID int identity primary key,
Name nvarchar(50),
Gender nvarchar(50),
Email nvarchar(50)
)
Creating Table In database |
//Inserting Demo Data
Here , we are inserting 4 Rows in Database tableinsert 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')
Inserting Data in Table |
Showing All Inserted Data
Download Database script fileCreate 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
Implementing Search Functionality in Asp.Net MVC 4 |
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 item2. Then select ADO.NET Entity Data Model --.> Give it a valid name like 'sampledatamodel'
3. Click Add
Implementing Search Functionality in Asp.Net MVC 4 |
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
Implementing Search Functionality in Asp.Net MVC 4 |
5. click next
6. Now in next dialog box you will be presented with tables available in database table select you table
Implementing Search Functionality in Asp.Net MVC 4 |
7. Now click Finish
8. Now Entity model of table is generated you can rename your database here to 'Employee'
Implementing Search Functionality in Asp.Net MVC 4 |
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
Implementing Search Functionality in Asp.Net MVC 4 |
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 autimatically add Views for insert , update, delete and index view in views folder under controller named folder
Implementing Search Functionality in Asp.Net MVC 4 |
Implementing Search Functionality in Asp.Net MVC 4 |
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 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
<div style='font-family:Arial'>
and close this div right below the code after table tag
Other UpdationAre in Demo Project Downlao And Use it
3. Update your Index.cshtml file under view folder in solution Explorer with the code below
@model IEnumerable<SearchInMVC.Models.Employee>
@{
ViewBag.Title = "Index";
}
<div style="font-family:Arial ">
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<p>
@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" />
}
</p>
<table border="1">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Gender)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th>Action</th>
</tr>
@if (Model.Count() == 0)
{
<tr>
<td colspan ="4">No Rows Match Search Criteria</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
}
</table>
</div>
Now Run your Application and you can see the change with output below :-
Implementing Search Functionality in Asp.Net MVC 4 |
Code Description
In code above we have used Razor code and instead of using <form> tag that we usually use in html we have used Html Helper below
@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 applied on data we are posting
Now Open Controller And Add code below to Index Action of home controller
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());
}