I\'m trying to pass JSON from jQuery to a .ASHX file. Example of the jQuery below:
$.ajax({
type: \"POST\",
url: \"/test.ashx\",
data: \"{\
The following solution worked for me:
Client Side:
$.ajax({
type: "POST",
url: "handler.ashx",
data: { firstName: 'stack', lastName: 'overflow' },
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: function (response) {
alert(response.d);
}
});
Server Side .ashx
using System;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string myName = context.Request.Form["firstName"];
// simulate Microsoft XSS protection
var wrapper = new { d = myName };
context.Response.Write(JsonConvert.SerializeObject(wrapper));
}
public bool IsReusable
{
get
{
return false;
}
}
}
This works for calling web services. Not sure about .ASHX
$.ajax({
type: "POST",
url: "/test.asmx/SomeWebMethodName",
data: {'file':'dave', 'type':'ward'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#Status').html(msg.d);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert('Error: ' + err.Message);
}
});
[WebMethod]
public string SomeWebMethodName(string file, string type)
{
// do something
return "some status message";
}