Wednesday, November 25, 2009

JavaScript Object via JQuery Ajax to an Asp.Net WebMethod

Given the following WebMethod

[WebMethod]
public static string UpdatePerson(Person person)
{
Person p = Repository.Instance.Get<Person>(person.Guid);
p.Name = person.Name;
p.Age = person.Age;
Repository.Instance.Update(p);

var result = new WebMethodResult<Person>();
result.Entity = p;
return result.ToJson();
}

[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string Modified { get; set; }
}

You can call this UpdatePerson method using the following jQuery code snippet.

function updatePerson() {
var request = {};
var person = {};
person.name = "Daffy Duck";
person.age = 12;
person.title = "Clown"; //Note that title is not a valid property
request.person = person;

var dataString = $.toJSON(request); //using jquery.json
$.blockUI();

$.ajax({
type: "POST",
url: "Default.aspx/UpdatePerson",
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(json) {
var data = eval('(' + json.d + ')');
if (data.hasErrors)
alert(data.message);
else {
alert("updated " + data.entity.Modified);
}

$.unblockUI();
}
});
}