AJAX Coding in ASP.NET Web Forms

ASPX Page

The ASPX page contains only the <%@ Page %> directive.

ASPX Code-Behind

Note these important elements in the following code.


[WebMethod]
public static OrderManagerResponse MethodName(AddItemsArgs args)
{
    var result = DoSomething(new Guid(args.ItemID), args.Quantity);
    return result;
}

public class AddItemsArgs
{
    public string ItemID { get; set; }
    public int Quantity { get; set; }
}

public class OrderManagerResponse
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public int CartItemCount { get; set; }
}

JavaScript Code

Note these important elements in the following code.


var objJSON = {
    args: {
        ItemID: itemID,
        Quantity: qty
    }
};

var encoded = JSON.stringify(objJSON);

$.ajax({
    type: 'POST',
    url: 'PageName.aspx/MethodName',
    contentType: 'application/json; charset=utf-8',
    data: encoded,
    processData: false,
    datatype: 'json',
    async: false,
    success: function (data) {
        if (!data.d.Success) {
            alert(data.d.Message);
        }
        else {
            $(".ShoppingCartQty").html(data.d.CartItemCount);
            highlightFlash('.ShoppingCart');
        }
    }
});