Search Functionality in ASP.NET MVC

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

Recommendation

Read Display Data in GridView Using Asp.net MVC before this article.

In this example we can use the entity data source for the getting the data from the database.when you run the project get  all data from the database and if you search data using the textbox then you get filter data  and display in gridview

Step 1 : First you create Mvc application

Step 2: Create database as following

database

Step 3:  Now you drag and drop database table and Create ADO.NET Entity Data Model as following.

entityframework

Step 4:  Now just time to Create  model class for data access  as following. and give name EmployeeData.cs

public class EmployeeData
{
public List<Product> ProductList { get; set; }

}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Education { get; set; }

}

Step 5: after creating model its time to add controller method as following code here you will be write the search functionality logic.

public class CBController : Controller
{

[HttpGet]
public ActionResult GridSearch()
{
EmployeeData EMP = new EmployeeData();
EMP.ProductList = GetProduct(“”);
return View(EMP);
}
[HttpPost]
public ActionResult GridSearch(string SearchData)
{
EmployeeData EMP = new EmployeeData();
EMP.ProductList = GetProduct(SearchData);
return View(EMP);
}

public List GetProduct(string SearchData)
{
List lst = new List();
Database1Entities6 db = new Database1Entities6();
var DataItem = from data in db.tbl_user
where SearchData == “” ? true : data.Name.StartsWith(SearchData)
select data;
foreach (var item in DataItem)
{
lst.Add(new Product
{
Id = (int)item.Id,
Name = item.Name,
City = item.City,
Education = item.Education

});
}
return lst;
}

Step 6: and then finely add the view as following with the gridview.

@model MvcApplication1.Models.EmployeeData

@{
ViewBag.Title = “GridSearch”;
}

<h2>GridSearch</h2>
<style>
table, td, th
{
border: 1px solid black;
}
th
{
border: 1px solid black;
background-color: pink;
}
</style>

@using (@Html.BeginForm())
{
<table>
<tr>
<td>
@Html.TextBox(“SearchData”, “”)
<input type=”submit” value=”SearchData” />
</td>
</tr>
</table>
var grid = new WebGrid(Model.ProductList, canSort: false);
<div>
@grid.GetHtml(columns:
grid.Columns
(
grid.Column(“Id”, “Id”),
grid.Column(“Name”, ” Name”),
grid.Column(“City”, “City”),
grid.Column(“Education”, “Education”)

), mode: WebGridPagerModes.Numeric)

</div>
}

 

When you run project gridview populate data as below

Search Functionality in ASP.NET MVC

Now filter data by input text into textbox

Search Functionality in ASP.NET MVC

SEE MORE