Click here to Skip to main content
15,883,558 members
Articles / Programming Languages / ASP
Tip/Trick

Autocomplete in ASP.NET MVC3

Rate me:
Please Sign up or sign in to vote.
4.75/5 (8 votes)
12 Mar 2012CPOL 49.6K   12   8
Autocomplete behaviour in a strongly typed view of ASP.NET MVC3
Provide a link:
HTML
<link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
 
write a script as:
C#
$(function () {
              function split(val) {
                  return val.split(/,\s*/);
              }
              function extractLast(term) {
                  return split(term).pop();
              }
 
              $("#NewAddress").bind("keydown", function (event) {
                  if (event.keyCode === $.ui.keyCode.TAB &&
                      $(this).data("autocomplete").menu.active) {
                      event.preventDefault();
                  }
              })
              $("#NewAddress").autocomplete({
                  source: function (request, response) {
                      //define a function to call your Action (assuming UserController)
                      $.ajax({
                          url: '/Controller/action', type: "GET", dataType: "json",
                          //query will be the param used by your action method
                          data: { query: request.term },
                          term: extractLast(request.term),
                          success: function (data) {
                              response($.map(data, function (item) {
                                  return { label: item, value: item };
                              }))
                          }
                      })
                  },
                  search: function () {
                      // custom minLength
                      var term = extractLast(this.value);
                      if (term.length < 1) {
                          return false;
                      }
                  },
                  focus: function () {
                      // prevent value inserted on focus
                      return false;
                  },
                  select: function (event, ui) {
                      var terms = split(this.value);
                      // remove the current input
                      terms.pop();
                      // add the selected item
                      terms.push(ui.item.value);
                      // add placeholder to get the comma-and-space at the end
                      terms.push("");
                      this.value = terms.join(", ");
                      return false;
                  }
              });
 
          });
 

In the view body write:
HTML
<%=Html.TextBoxFor(m => m.NewAddress)%>
 
in the controller :
C#
public ActionResult GetEmailIds(string query)
       {
           query = query.Replace(" ", "");
           if (query.Length > 1)
           {
               int op = query.LastIndexOf(",");
               query = query.Substring(op + 1);
           }
           var users = (from u in _userService.GetAllUsers()
                        where u.EmailAddress.Contains(query)
                        orderby u.EmailAddress // optional
                        select u.EmailAddress).Distinct().ToArray();
 
           return Json(users, JsonRequestBehavior.AllowGet);
       }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Other Other
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionA huge thank Pin
Member 1065006926-Mar-14 23:29
Member 1065006926-Mar-14 23:29 
GeneralMy vote of 3 Pin
kathir831-Apr-13 2:51
kathir831-Apr-13 2:51 
GeneralMy vote of 5 Pin
R J Vidya12-Feb-13 0:23
R J Vidya12-Feb-13 0:23 
Questiongreate post Pin
Etibar HASANOV21-Nov-12 2:14
Etibar HASANOV21-Nov-12 2:14 
QuestionFunction not running working Pin
Member 929708424-Jul-12 23:36
Member 929708424-Jul-12 23:36 
AnswerRe: Function not running working Pin
Diliposv22-Feb-13 19:36
Diliposv22-Feb-13 19:36 
GeneralReason for my vote of 5 really useful for ASP.NET developers Pin
Nikhil_S1-Mar-12 17:53
professionalNikhil_S1-Mar-12 17:53 
GeneralRe: Reason for my vote of 5really useful for ASP.NET developers Pin
member6023-Apr-12 18:45
member6023-Apr-12 18:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.