View Single Post
  #6 (permalink)  
Old November 17th, 2009, 08:21 AM
Imar's Avatar
Imar Imar is offline
Wrox Author
Points: 72,073, Level: 100
Points: 72,073, Level: 100 Points: 72,073, Level: 100 Points: 72,073, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,089
Thanks: 80
Thanked 1,587 Times in 1,563 Posts

Yeah, that would work. Or you can use PageMethods that allow you to pass back and forth complex objects. Here's a simple example that asks a user for a product ID, creates a Product instance (which is defined in the Code Behind class) and passes it to AddToOrder (which is defined as a static method in the Code Behind and has the WebMethod attribute applied.) Note: you also need a ScriptManager with EnablePageMethods set to true:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
 <script type="text/javascript">
  function AddProductToOrder(id)
   var myProduct = new Product();
   myProduct.Id = id;
   myProduct.Name = "Some Value";
   PageMethods.AddToOrder(myProduct, SuccessCallback);
  function SuccessCallback(result)
   alert('Order ID is ' + result);
 <form id="form1" runat="server">
  <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
  <input onclick="AddProductToOrder(prompt('Id'));" id="Button1" type="button" value="Add to order" />
using System;
using System.Web.Services;
public class Product
 public string Id { get; set; }
 public string Name { get; set; }
public partial class _Default : System.Web.UI.Page
 public static string AddToOrder(Product product)
  // TODO add logic here. Right now, for this example
  // I simply return the product Id and some constant value
  return "Test " + product.Id;
Hope this helps,

Imar Spaanjaars
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!