Search and Filter data in Gridview using Asp.net MVC

Search and Filter data in Gridview using Asp.net MVC

In this article we have learn about how to Search and Filter data in Gridview using Asp.net MVC,for this i have used sql server database and sql query for search or filter data from database, and this filter data are displaying in grid using razor view.

Step 1 : first Create Model and database field name as below

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

}

Step 2 : Now Create Controller and add the following code and create action method.

public SqlConnection con = new SqlConnection(con);

public List<DAL> Select_data()
{
List<DAL> D = new List<DAL>();
try
{
con.Open();
SqlCommand cmd = new SqlCommand(“select * from tbl_user”, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DAL da = new DAL();
da.Id = Convert.ToInt32(dr[“id”].ToString());
da.Name = dr[“Name”].ToString();
da.City = dr[“City”].ToString();
da.Education = dr[“Education”].ToString();
D.Add(da);
}
con.Close();
}
catch (Exception)
{
}

return D;
}

[HttpGet]
public ActionResult SearchGrid()
{
return View(Select_data());
}

[HttpPost]
public ActionResult SearchGrid(string SearchKey)
{
List<DAL> D = new List<DAL>();
DAL dd=new DAL();
var data = (from m in Select_data() where m.Name.StartsWith(SearchKey, StringComparison.OrdinalIgnoreCase) select new { m.Name, m.City, m.Education }).ToList();

foreach (var V in data)
{
D.Add(new DAL {
Name = V.Name,
City = V.City,
Education = V.Education
});
}
return View(D);
}

Step 3 :Now Create View For display Gridview as Following

@model  IEnumerable<MVC4_Search_In_Grid.Models.DAL>

@{
ViewBag.Title = “Search”;
}

@using (@Html.BeginForm())
{
<table>
<tr>
<td>
@Html.TextBox(“SearchKey”, “”)

</td>
<td>
<input type=”submit” value=”Search” />
</td>
</tr>
</table>
<table>
<tr>
<th>
Name
</th>
<th>
City
</th>
<th>
Education
</th>
</tr>
<tbody>
@foreach (var item in Model)
{
<tr id=”tr1″>
<td>
@item.Name
</td>
<td>
@item.City
</td>
<td>
@item.Education
</td>
</tr>
}
</tbody>

</table>

}

Search and Filter data in Gridview using Asp.net MVC

 

Search and Filter data in Gridview using Asp.net MVC

SEE MORE