Create AutoComplete TextBox with ASP.NET, C# and jQuery UI

AutoComplete - It is  suggests text automatically based on the first few characters that a user types.
Step:1 Add following code in "default.aspx" page.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> 
<script type="text/javascript">
$(function () {
   $("[id$=txtAuto]").autocomplete({
   source: function (request, response) {
   $.ajax({
      url: "NameList.asmx/GetNameList", 
      data: "{ 'Name': '" + request.term + "' }",
      dataType: "json",
      type: "POST", 
      contentType: "application/json; charset=utf-8",
      async: true,
      success: function (data) {               
                   var Details = [];
                   for (i = 0; i < data.d.length; i++) {
                         Details[i] = data.d[i].Name;
                                 } response(Details);
                        },
      error: function (result) {
                         }
          });
       }
    });
});
</script>

Add HTML Code:

1
2
3
4
5
6
7
<div class="demo">
    <div class="ui-widget">
       <label for="txtAuto">Enter Name: </label>
       <asp:TextBox ID="txtAuto" runat="server">
       </asp:TextBox>
    </div>
</div>

Step:2 Add Web Service and write following code in it.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[WebMethod]
public List<UserNameList> GetNameList(string Name)
{ 
  var emp = new UserNameList();  
  var fetchName = emp.GetEmpList()
  .Where(m => m.Name.ToLower().StartsWith(Name.ToLower()));  return fetchName.ToList();       
}

public class UserNameList
{
  public int ID { get; set; } 
  public string Name { get; set; }
  public List<UserNameList> GetEmpList() 
  {
      List<UserNameList> emp = new List<UserNameList>();
      emp.Add(new UserNameList() { ID = 1, Name = "Arjun" });  
      emp.Add(new UserNameList() { ID = 2, Name = "Aaryan" });
      emp.Add(new UserNameList() { ID = 3, Name = "Anoop" });  
      emp.Add(new UserNameList() { ID = 4, Name = "Bob" });
      emp.Add(new UserNameList() { ID = 5, Name = "Boby" });
      emp.Add(new UserNameList() { ID = 6, Name = "Cristen" });  
      emp.Add(new UserNameList() { ID = 7, Name = "Cris" });
      return emp;
  }
}


Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment