Data Filtering Using AJAX Form In Asp.Net MVC Development

This post is created by MVC developers to make you learn how to filter data using AJAX form in mvc development. Experts have put their skills in use to explain how data will filter and display with the help of partial view asynchronously. Follow the steps and perform data filtering like professionals.


This article explain how to filter record using Ajax.BeginForm in MVC. We have attempted to explain how data will filter and display using partial view asynchronously. Simply we have created two Repoclasses to store products and category records and in product page I filter and load records when click on search button in MVC Ajax.BeginForm.

In addition I will also explain you how we can display loader image(progressbar) when ajax request is begin and hide loader function when ajax request is completed.

Code Behind:

Follow the following steps.

Step 1: Create a simple MVC application. Currently I am going to create MVC application using Visual Studio 2015.Create a simple MVC application

Step 2: Create CategoryModel and ProductModelas like below in Model folder.

publicint Id { get; set; }

publicstring Name { get; set; }

publicint Id { get; set; }

publicint CategoryId { get; set; }

publicstring Name { get; set; }

publicint Quantity { get; set; }

publicint Price { get; set; }

CategoryId : Is used to POST selected Category from Dropdown to the controller method.

CategoryList: Is used to fill up list of Categories in Category Dropdown, so user can select category and post to the controller method.

SearchText: Is used to post search text to the controller method to search out product name.


Step 4:  Create a Code folder and add CategoryRepo and ProductRepo class display like below.This classes are used to fetch product and category data. ExtensionHelper class  described in Step4.










  • CategoryRepo class have a GetAll() methods which return List<CategoryModel>.You can see below I have added some test data and that I return in GetAll() method.
        [Display(Name = "Select Category")]
publicint CategoryId { get; set; }

publicList CategoryList { get; set; }

        [Display(Name = "Search Text")]
publicstring SearchText { get; set; }
  • ProductRepo class have a GetAll() methods which return List<ProductModel>. You can see below I have added some test data and that I return in GetAll() method.
publicList GetAll()
newProductModel() {Id = 1, CategoryId = 1, Name = "Samsung Galaxy On5 (Gold, 8 GB)", Price = 8160, Quantity = 1},
newProductModel() {Id = 2, CategoryId = 1, Name = "Samsung Guru E1200 (Black)", Price = 1230, Quantity = 5},
newProductModel() {Id = 3, CategoryId = 1, Name = "Samsung Galaxy J1 Ace (White, 4 GB)", Price = 6400, Quantity = 3},
newProductModel() {Id = 4, CategoryId = 1, Name = "Samsung Tizen Z3 (Gold, 8 GB)", Price = 8850, Quantity = 8},

newProductModel() {Id = 5,CategoryId = 2, Name = "Lenovo Sisley S60 (Graphite Grey, 8 GB) ", Price = 9000, Quantity = 10},
newProductModel() {Id = 6,CategoryId = 2, Name = "Lenovo A1000 (Black, 8 GB)", Price = 3950, Quantity = 6},
newProductModel() {Id = 7,CategoryId = 2, Name = "Lenovo K3 Note (White, 16 GB)", Price = 9199, Quantity = 2},

newProductModel() {Id = 8,CategoryId = 2, Name = "Lenovo A2010 (Black, 8 GB)", Price = 4990, Quantity = 0},
newProductModel() {Id = 9,CategoryId = 2, Name = "Lenovo A6000 Plus (Red, 16 GB)", Price = 6999, Quantity = 5},

newProductModel() {Id = 10, CategoryId = 3, Name = "Apple iPhone 5S (Space Grey, 16 GB)", Price = 19299, Quantity = 5},
newProductModel() {Id = 11, CategoryId = 3, Name = "Apple iPhone 6S (Rose Gold, 16 GB)", Price = 42999, Quantity = 2},
newProductModel() {Id = 12, CategoryId = 3, Name = "Apple iPhone 6 (Silver, 16 GB)", Price = 35999, Quantity = 1},

newProductModel() {Id = 13, CategoryId = 4, Name = "Moto X Play (White, 16 GB) ", Price = 16999, Quantity = 15},
newProductModel() {Id = 14, CategoryId = 4, Name = "Moto X (2nd Generation) (Black, 16 GB)", Price = 14999, Quantity = 9},
newProductModel() {Id = 14, CategoryId = 4, Name = "Moto G (3rd Generation) (White, 16 GB)", Price = 10999, Quantity = 3},
newProductModel() {Id = 16, CategoryId = 4, Name = "Moto G (Black, 16 GB)", Price = 9400, Quantity = 1},

newProductModel() {Id = 17, CategoryId = 5, Name = "Mi 4 (White, 16 GB)", Price = 14999, Quantity = 20 },
newProductModel() {Id = 18, CategoryId = 5, Name = "Redmi 2 Prime (White, 16 GB)", Price = 6999, Quantity = 5},

Step 5: Create anExtensionHelperstatic class in Code folder. This class is used to convert List to List.We are populate category list in dropdown using this method.

publicstaticList ToSelectList(thisList Items, Func<T, string> Text,
Func<T, string> Value, string selectedValue, string DefaultText, bool DefaultOption = false)
List items = newList();

if (DefaultOption)
                    Selected = true,
                    Value = "-1",
                    Text = string.Format("-- {0} --", DefaultText)

foreach (var item in Items)
                    Text = Text(item),
                    Value = Value(item),
                    Selected = selectedValue == Value(item)

return items
                .OrderBy(l => l.Text)

In above code we have created ToSelectList extension method. This method accept following parameters.

  • thisList<T> Items :Is the list which we want to convert inList<SelectListItem>
  • Func<T, string> Text: Is the text field which we want to display in dropdown as list.
  • Func<T, string> Value: Is the value field which we want to set option value of dropdown.
  • string selectedValue: Is determine which value we want to set selected in dropdown.
  • string DefaultText: Is used to add default option in dropdown.
  • bool DefaultOption = false: Is used to add default option in dropdown.


Step 6:  Create SearchProductControllerand add Index method as like below.

publicActionResult Index()
SearchModel model = newSearchModel();

CategoryRepo repo = newCategoryRepo();
            model.CategoryList = repo.GetAll().ToSelectList(s => s.Name, s => s.Id.ToString(), "-1", "Select", true);
return View(model);

In above code we create a SearchModel model which is passed to the Index View and fill up Category Dropdown. By Default Category Dropdown has “—Select—“ option selected.

Step 6: Create LoadProducts method in SearchProductControllerwhich return ProductsView partial view and load all product list in Index view at page load.

publicActionResult LoadProducts()
ProductRepo repo = newProductRepo();
return PartialView("ProductsView", repo.GetAll());

Step 7: Create FilterProductsmethod in SearchProductControllerwhich is used to filter product by fields which we set in Index view. This method pass searchItem list to ProductView partial view and this partial view return back to the Index view and display filtered product.

publicActionResult FilterProducts(SearchModel model)
ProductRepo repo = newProductRepo();
List productsList = repo.GetAll();
var searchItmes =
                    s => (model.CategoryId <= 0 || s.CategoryId == model.CategoryId) &&
                         (string.IsNullOrEmpty(model.SearchText) || s.Name.Contains(model.SearchText))).ToList();
return PartialView("ProductsView", searchItmes);

Step 8: Create Index.cshtml and ProductsView.cshtml in SearchProduct folder as like below.




  • You can see in above code we take Ajax.BeginForm which is post when user click on Submit button. At the time of form submit “FilterProducts” method of “SearhProduct” controller is called which return ProductsView and replace html in ProductListdiv.



  • This Partial View is used to display Product list.

Step 9: Now, all code is completed. So, run the application and go to “SearchProduct” page. You can see following output on your browser.


  • At the top of the page we can see the filter controls, and bottom we can see the all products.
  • Have you see? When you click on Submit button? The form is post and page will refresh. That is because we have to include “jquery.unobtrusive-ajax” jQuery file in our layout. So, we are going to next step.


Step 10: Add Microsoft.jQuery.Unobtrusive.Ajax plugin from Nuget Package manager. To add “Microsoft.jQuery.Unobtrusive.Ajax” package in MVC application, follow the below steps.

  • Right click on Solution -> Click on Manage Nuget Package.
  • Go to Browse section and search with “Microsoft.jQuery.Unobtrusive.Ajax”.
  • Click on Install button.


  • After successfully install package you can that in Scripts folder two jQuery files is added.
    • unobtrusive-ajax.js
    • unobtrusive-ajax.min.js


  • Also make sure following setting should be in web.config file. If not exists then add it.
<addkey="webpages:Version"value="" />
<addkey="webpages:Enabled"value="false" />
<addkey="ClientValidationEnabled"value="true" />
<addkey="UnobtrusiveJavaScriptEnabled"value="true" />

- Now, go to BundleConfig.cs file which is present in App_Start folder. Add following bundle in RegisterBundles method.


- Go to _Layout.cshtml which is under Shared folder and add recently created bundle at the bottom of page.


- Run application again, and select any category from category dropdown and click on search button. You can see that Products grid will filter out by category which you selected asynchronously.

Step 11: Filter is working fine, now we need to clear out the filter and load all products when user click on Clear button. To do this, follow the below steps.

- Create a site.js file under Scripts folder.
- Add following method in site.js file as below.

$(document).ready(function() {
	$('#clearSearch').click(function() {

- Now when you click on Clear button, Category Dorpdown default option is selected and SearchText box is clear out as well.

Step 12: Product filter is done. But when user click on search button the process is running in background. So, user does not get idea that user click on search button an filter is in progress? Or user think that search filter is working or not. So we need to display progress bar when user click on search button and after result is displayed we need to hide that progress bar. This issue occurred when data filter method take some time to filter record.

To avoid this issue I am going to add “jquery.loadmask” plugin. Masking is a process to display progress bar while content is loading or background process is running, inform to the end user that background process is still running.

To add loadmask plugin in our application follow the following steps.
- Download LoadMask jQuery plugin here.
- Add “jquery.loadmask.min.js” in the Scrips folder.
- Add jquery.loadmask.min.js file in site bundle in BundleConfig.cs file as below.


- Create a img folder under Content folder.
- Add loader image which you want and put downloaded image in img folder which you recently created, this image is displays when you click on search button. You can download ajax loader image here(“”)
- Add following styles in Site.css file which is under Content folder

.loadmask{ z-index: 100; position: absolute; top:0; left:0; -moz-opacity: 0.5; opacity: .50; filter: alpha(opacity=50);
background-color: #CCC; width: 100%; height: 100%; zoom: 1; cursor:wait; }
.loadmask-msg{ z-index: 20001; position: absolute; top: 0; left: 0;  }
.loadmask-msgdiv{ background:url(img/ajax-loader.GIF)00no-repeat; height:36px; width:36px; }
.masked{ overflow: hidden!important; }
.masked-relative{ position: relative!important; }
.masked-hidden{ visibility: hidden!important; }

- In above code replace image file namebackground:url(img/ajax-loader.GIF)here which you download for displaying as a progress bar.

LoadMask plugin is added in our MVC application, now we need to mask div element when ajax request is begin and unmask div element when ajax request is complete. Below step describe you how to achieve this scenario.
- Replace following line in Index.cshtml file.

@using (Ajax.BeginForm("FilterProducts", "SearchProduct", null, newAjaxOptions() { OnComplete = "SearchComplete", OnBegin = "SearchBegin", UpdateTargetId = "ProductList" }, new { @class = "form-inline" }))

- In above code you can see we added OnComplete and OnBegin AjaxOptions.
o OnBegin : Gets or sets the name of the JavaScript function to call immediately before the page is updated.
o OnComplete: Gets or sets the JavaScript function to call when response data has been instantiated but before the page is updated.
- Add SearchBegin and SearchComplete function in site.js file as per following.

$(document).ready(function() {
    $('#clearSearch').click(function() {

functionSearchBegin() {
    $('div.products').mask(" ");

functionSearchComplete() {

- Now run application. When you click on Submit button you can see progress bar image as like below.


Conclusion: By above blog we learn following things.

  • How to filter data using Ajax.BeginFormin MVC.
  • How to display ajax-loader progressbar when ajax request begin using LoadMask jQuery plugin.


You got right steps to understand the process of data filtering. You can now filter data using AJAX form in MVC development and share your experience with other readers.

Author Bio:

This article has been shared by Ethan Millar, working with Aegis SoftTech as technical writer from last 5 years. He especially write articles for Java, .Net, CRM and Hadoop. The objective to write this article is to discuss Data Filtering Using AJAX Form In Asp.Net MVC Development. You can find Ethan Millar here in Facebook and Google Plus.

Leave a Reply

Your email address will not be published. Required fields are marked *