Download Sample project from following link (Project Type: VS 2012 ASP.net MVC4)
http://sdrv.ms/14hsdoO
One of my folk requested to me to make a sample project on ASP.net MVC to show how to filter record from table. Here is the request from him;

Search by (LastName, FirstName, etc.. this value should be in a dropdown)
—- but it actually came from a search parameter table. It’s kind of a lookup table in a dropdown
Besides the dropdown there should be textbox where I can enter a value
Search by LastName (dropdown) <”hasibul”> in textbox

Here I will try to show 2 different way for filtering data ( How to perform search or filter ).
Way 1 : Based on request.
Way 2: In my project how I filter data from table.
So let’s start way 1:
Things need to do
> Need to populate a drop down list with filter type/ Search type, which will come from another table.
> Need to pass view data to controller and populate the search result on view.
Let’s do..
Consider we have following entities

public class SearchParameter
    {
        [Key]
        public int Id { get; set; }
        public string ParameterName { get; set; }
    }

And

 public class Student
 {
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string RollNo { get; set; }
 }

Search parameter consist of search by field and we will populate dropdown list with the collection of SearchParameter.

Then we will perform filter on students (List of student).

Lets create our view

Filter or Search record from collection of data using ASP.net MVC
Filter or Search record from collection of data using ASP.net MVC
@model IEnumerable<SimpleSearchApp.Models.Student>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@using (@Html.BeginForm("Filter", "student"))
{
@Html.DropDownList("SearchParameters")
@Html.TextBox("txtFilter")
<input type="submit" value="Search" />
}
</p>
<table>
</table>

And our filter method is following

[HttpPost]
        public ActionResult Filter(FormCollection formCollection) 
        {

            var students = new List();
            var filterBy = formCollection.Get("SearchParameters");
            var filterText = formCollection.Get("txtFilter");

            switch (filterBy) 
            {
                case "FirstName":
                    students = db.Students.Where(p => p.FirstName.Contains(filterText)).ToList();
                    break;
                case "LastName":
                    students = db.Students.Where(p => p.LastName.Contains(filterText)).ToList();
                    break;
            }

            ViewBag.SearchParameters = new SelectList(db.Parameters.ToList(), "ParameterName", "ParameterName");
            return View("Index",students);
        }

View data are submitted to controller and from controller we have performed filter and after filtering filtered data are passed to index method for showing on Index.

That’s it.
Using above way we have to load filter by dropdown list every time and page will refresh after pressing search button.

Way 2 : Performing filter using ajax post and partial view.
Let’s do filter another way where page will not refresh every time; only table will be update.
Here we have to create a partial view which will update after pressing filter search button.
Lets create partial view

@model IEnumerable<SimpleSearchApp.Models.Student>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.RollNo)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.RollNo)
</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>

Then render this partial view from index view in following way

@Html.TextBox("txtFilter")
<input type="button" value="search" onclick="filter()" />
<br />
<div id="tblStudents">
@Html.Partial("_students", Model)
</div>

Now post filter data by ajax post instead of form submit.

<script type="text/javascript">
function filter() {
$.ajax({
type: "POST"
, url: "Student2/Filter"
, data: JSON.stringify({ filterText: $("#txtFilter").val() })
, contentType: 'application/json;'
, success: function (result) {
$("#tblStudents").html(result);
}
});
}
</script>

Filter method will accept the request and return partial view as a result.

Then this result will be loaded on div.

[HttpPost]
        public ActionResult Filter(string filterText) 
        {
            var students = new MyDbContext().Students.Where(p=> 
                    p.FirstName.Contains(filterText) 
                ||  p.LastName.Contains(filterText)
                ||  p.RollNo.Contains(filterText)
                ).ToList();
            return PartialView("_students", students);
        }

Download Sample project from following link (Project Type: VS 2012 ASP.net MVC4)
http://sdrv.ms/14hsdoO

  • Lhay

    Hi Mohammad,

    It did work. Thank so much.

    I had to change it a little bit from

    @Html.DisplayNameFor(model => model.FirstName)

    TO

    FirstName

    • hasibul2363

      glad to hear that it wroks for you.

  • prince bajaj

    not suffiecient information provided it will work or not ,i ,m not sure… if you have any other way to do this please let me know !!!!!!!!!

    • hasibul2363

      let me know if it doesn’t work. You also check the given source…

  • Sagar Patil

    I want filtering of Webgrid otrhtml table with drop down list which contaons categories i did it with partial view but after partial view loaded css and js not working.so give me ant sample code that works fine

  • Pratham Dave

    it doesn’t work…

    • can you share what error you are getting?

      • Pratham Dave

        Can you send me source code. because i am working on umbraco CMS, and in that I want to simply implement search functionality.

        by ajax, json which you have define above.

        Thanks.

      • Muhammad Khan

        Can you please modify this code as i just want to filter my list selected value from dropdownlist e.g.
        Recently added records
        Today Added Records
        Like this
        Thank you