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
Default

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:

Default.aspx
Code:
<%@ 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>
 <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);
  }
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
  <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
  </asp:ScriptManager>
  <input onclick="AddProductToOrder(prompt('Id'));" id="Button1" type="button" value="Add to order" />
 </div>
 </form>
</body>
</html>
Default.aspx.cs
Code:
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
{
 [WebMethod]
 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
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
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!