View Single Post
  #7 (permalink)  
Old November 20th, 2009, 06:01 AM
elwappo elwappo is offline
Authorized User
Points: 192, Level: 3
Points: 192, Level: 3 Points: 192, Level: 3 Points: 192, Level: 3
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Aug 2006
Location: God's country , United Kingdom.
Posts: 41
Thanks: 1
Thanked 0 Times in 0 Posts
Default

Quote:
Originally Posted by Imar View Post
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
Thanks for that Imar - I've used a web method with the autocomplete extender, which is what got me thinking about the context key.

One thing that I noticed with the autocomplete extender is that the web method you declare must have the signature (string prefixText, string contextKey) which means you can clearly access the context value server side.

This is what confused me and brought about my initial post!