Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

AJAX Coding in ASP.NET Web Forms

RSS
Modified on Thu, Apr 19, 2012, 8:24 AM by Administrator Categorized as 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.

  • The method is decorated with the [WebMethod] attribute.
  • The function signature is marked public static.

[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.

  • The itemID and qty variables are set prior to this code running.
  • The objJSON object is the JavaScript parallel to the pararmeter in the AJAX method: in this case, the AddItemsArgs class.
  • In the $.ajax() call, the URL property consists of the PageName.aspx, which is the full path to your ASPX page, plus a MethodName, which corresponds to the name of the method that will return data for your AJAX call.
  • In the success function, elements of the returned object are accessed via data.d instead of via data. Note that the data.d object is the JavaScript parallel to the return type of the AJAX method: in this case, the OrderManagerResponse class.
  • The highlightFlash function is defined elsewhere.

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');
        }
    }
});

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.