You could use ASPX PageMethods with jQuery. So start working on the server by defining a model:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
then you could define a page method in some aspx page (/foo.aspx
):
public partial class _Foo : System.Web.UI.Page
{
[WebMethod]
public static string SavePerson(Person p)
{
// do some processing with the person
return "Hello World";
}
}
and finally invoke this page method:
var p = {
firstName: 'John',
lastName: 'Smith'
};
$.ajax({
url: '/foo.aspx/SavePerson',
type: 'POST',
contentType: 'application/javascript; charset=utf-8',
data: JSON.stringify(p),
success: function(result) {
alert(result.d);
}
});
The JSON.stringify method illustrated here is built in modern browsers. If you need to support legacy browsers you could include the json2.js script to your page.
UPDATE:
As requested in the comments section here's how you could design a generic ASHX handler that will receive this request, do some processing and return a JSON response:
public class Foo : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var serializer = new JavaScriptSerializer();
using (var reader = new StreamReader(context.Request.InputStream))
{
Person person = (Person)serializer.Deserialize<Person>(reader.ReadToEnd());
// do some processing with the person
}
context.Response.ContentType = "application/json";
var result = serializer.Serialize(new { data = "Hello World" });
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
}
and the request:
var p = {
firstName: 'John',
lastName: 'Smith'
};
$.ajax({
url: '/foo.ashx',
type: 'POST',
data: JSON.stringify(p),
success: function(result) {
alert(result.data);
}
});