Friday 18 May 2012

Example of AutoComplete text box with ASP.NET using jQuery and json

Add a web service in your project  and code of web service is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    DataClassesDataContext o = new DataClassesDataContext();
    public WebService ()
    {
    }
   [WebMethod]
    public List<EMP> x(string s)
    {
        var m = from x in o.EMPs where x.NAME.ToLower().StartsWith(s.ToLower()) select x;
        return m.ToList();
    }
   
}

Then design the page like this code is

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<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">
    $(document).ready(
    function () {
        $(function () {
            $(".tb").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "WebService.asmx/x",
                        data: "{ 's': '" + request.term + "' }",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    value: item.NAME
                                }
                            }))
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                },
                minLength:1
            });
        });
    }
)
  
</script>
</head>
<body>
    <form id="form1" runat="server">
    <table align="center">
    <tr><td>
     <div class="demo">
   <div class="ui-widget">
     <asp:TextBox ID="tbAuto" class="tb" runat="server">
     </asp:TextBox>
</div>
</div>
    </td></tr>
    </table>
  
    </form>
</body>
</html>





No comments:

Post a Comment