Friday 23 October 2015

Understand jQuery Ajax Function :- Call Server Side Code using ASP.NET AJAX and jQuery AJAX

In this article we will learn how to implement an ajax method in jQuery and populate the dropdown list through the jquery ajax methed. In the next article we will describe all the parameter like type: "POST",url: "Default.aspx/GetCustomers",data: '{}', contentType: "application/json; charset=utf-8", dataType: "json" and why we use.

HTML Markup
The following HTML Markup consists of an ASP.Net DropDownList.
<asp:DropDownList ID="ddlCustomers" runat="server">
</asp:DropDownList>
  
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;

The WebMethod
The following WebMethod gets the list of Customers from the Customers table and then creates a generic list of ListI tem class. In each object of List Item, the Customer Name is set in the Text part and the CustomerId is set in the Value part.
Finally the generic list of List Item objects is returned.
C#
[WebMethod]
public static List<ListItem> GetCustomers()
{
    string query = "SELECT CustomerId, Name FROM Customers";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            List<ListItem> customers = new List<ListItem>();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new ListItem
                    {
                        Value = sdr["CustomerId"].ToString(),
                        Text = sdr["Name"].ToString()
                    });
                }
            }
            con.Close();
            return customers;
        }
    }
}
Populating DropDownList Items (Options) on Client Side using jQuery
Inside the document ready event handler of the jQuery, first the WebMethod is called using jQuery AJAX function.
Inside the Success event handler of the jQuery AJAX function, first the ASP.Net DropDownList is referenced and a default Item (Option) is added to it.
Then a jQuery each loop is executed over the JSON array and one by one each item is added as an Option element to the DropDownList.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetCustomers",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var ddlCustomers = $("[id*=ddlCustomers]");
            ddlCustomers.empty().append('<option selected="selected"    value="0">Please select</option>');
            $.each(r.d, function (){
                ddlCustomers.append($("<option>   </option>").val(this['Value']).html(this['Text']));
            });
         
            error: function (Result) {
            alert("Error");
        }
    });
});
</script>
Don't forget to enable the attribute [System.Web.Script.Services.ScriptService], and add the [Web Method] attribute before the function definition.

No comments:

Post a Comment