Tuesday, March 13, 2012

Autocomplete dropdown with Jquery Ui and Asp.net MVC3

You probably know about Jquery UI autocomplete dropdown. It helps you to load long list with search params. You dont need to load all the values to the page. Dropdown list will load on demand.

I copied my notes here to remember next time i need to use it:

You can get the latest jquery ui js and css files from http://jqueryui.com. You should select autocomplete option to have this feature.

First, you need to set a reference to Jquery scripts in your page:


   1:   <link href="@Url.Content("~/Content/themes/ui-lightness/jquery-ui-1.8.18.custom.css")" rel="stylesheet" type="text/css" />
   2:  <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
   3:  <script src="@Url.Content("~/Scripts/jquery-ui-1.8.18.custom.min.js")" type="text/javascript"></script>
   4:   
   5:  <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
   6:  <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

Copy related theme and src files to related directories in your project.

Step2: You need to add your textbox to your page:


   1:  <div class="ui-widget">
   2:              <label for="customerdropdown">
   3:                  Customer:
   4:              </label>
   5:              <input id="customerdropdown" />
   6:          </div>
   7:          <div class="ui-widget" style="margin-top: 2em; font-family: Arial">
   8:              Result:
   9:              <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content">
  10:              </div>
  11:          </div>

Step3: Define actions in your js file:

   1:  <script>
   2:      $(function () {
   3:          function log(message) {
   4:              $("<div/>").text(message).prependTo("#log");
   5:              $("#log").scrollTop(0);
   6:          }
   7:   
   8:          $("#customerdropdown").autocomplete({
   9:              source: "/PhoenixEvent/GetCustomers/",
  10:              minLength: 2,
  11:              select: function (event, ui) {
  12:                  log(ui.item ?
  13:                      "Selected: " + ui.item.value + " aka " + ui.item.id :
  14:                      "Nothing selected, input was " + this.value);
  15:              }
  16:          });
  17:      });
  18:      </script>

Step4: You should have method in your controller to provide this list for each search term.


   1:    public JsonResult GetCustomers(string term)
   2:          {
   3:              //Phoenice company
   4:              int companyid = GetValidCompanyId();
   5:              //max 1000
   6:              var customers = db.Customers.Where(a=>a.CompanyId == companyid && (a.first_name.Contains(term) || a.last_name.Contains(term) ) ).Take(1000).ToList();
   7:              
   8:              List<object> dropDownInfos = new List<object>();
   9:   
  10:              customers.ForEach(t=>{dropDownInfos.Add(new 
  11:                                                          {
  12:                                                               id = t.CustomerId,
  13:                                                               label = t.first_name + " " + t.last_name,
  14:                                                               value = t.first_name + " " + t.last_name,
  15:                                                          });});
  16:              return Json(dropDownInfos,JsonRequestBehavior.AllowGet);
  17:          }

Don't forget the JsonRequestBehavior.AllowGet parameter in the Json call. You won't get anything back from the action method if you leave it off. You should return Json object with "id","value",and "label" columns.

Also, the name of the parameter passed into the action method is important. The jQuery UI autocomplete method will call your source URL with a query string like "?term=yoursearch". If you set the parameter name to a string named "term", the MVC model binder will grab the value from the query string for you.

NExt step is actually plug in this autocomplete to your real input param. You can do that in select action which we were just printing in log. You can get the selected value and update the actual field.

The jQuery UI Autocomplete function has several other options and events you can use in your app, and the demos are worth checking out too.

No comments:

Post a Comment

Hey!
Let me know what you think?