Monday, August 27, 2012

Pass Complex Data / Class / Form to WebMethod with PageMethods / Ajax

http://encosia.com/using-complex-types-to-make-calling-services-less-complex/
this is how to use JS / JQuery to make an object to JSON and pass it to a webmethod

but id i want to use PageMethods?
it even simpler - just pass the object as is
[WebMethod]
public static void AddPerson2(Person NewPerson)
{
   NewPerson.Add();
}
public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Address { get; set; }
  public string City { get; set; }
  public string State { get; set; }
  public string Zip { get; set; }
  public void Add()
  {     // Magic happens here.
  }
}


Client Side:

var NewPerson = new Object();
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();

PageMethods.AddPerson2(NewPerson , OnPageMethodComplete);

So lets make the most of it, or my original will - post a form in ajax:

function SendDataJson() {
   var myform = document.getElementById("formCreateNewUser");
   var nodes = myform.getElementsByTagName("input");
   var userDetails = {};
   for (var i = 0; i < nodes.length; i++) {
       if (nodes[i].type != 'text') { continue; }
       userDetails[nodes[i].id] = nodes[i].value;
   }
   PageMethods.CreateUserWebMethodFormObject(userDetails, OnCreateComplete);
}



No comments:

Post a Comment