POST json object array to IHttpHandler

别来无恙 提交于 2019-12-21 06:45:54

问题


Im constructing an array of objects like this:

var postData = [];

$.each(selectedFields, function (index, value) {
    var testTitle = 'testing ' + index;
    postData.push({title: testTitle, title2 : testTitle});        
}

I then post it like this(note that i have tried a number of different aproaches):

$.post('SaveTitlesHandler.ashx', { form : postData }, function (data) {
    console.log(data);
});

I then try to get the data in a handler...

public class SaveTitlesHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string json = context.Request.Form.ToString();
    }

}

I cant seem to get proper json out of the request. Anyone got any idea?

cheers.

twD


回答1:


You are not posting JSON. You are using application/x-www-form-urlencoded. So inside the handler you could access individual values:

public void ProcessRequest(HttpContext context)
{
    var title1 = context.Request["form[0][title]"];
    var title2 = context.Request["form[0][title2]"];

    var title3 = context.Request["form[1][title]"];
    var title4 = context.Request["form[1][title2]"];

    ...
}

If you wanted to POST real JSON you need this:

$.ajax({
    url: 'SaveTitlesHandler.ashx',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(postData),
    success: function(result) {
        console.log(result);
    }
});

and then inside the handler read from the request input stream:

public void ProcessRequest(HttpContext context)
{
    using (var reader = new StreamReader(context.Request.InputStream))
    {
        string json = reader.ReadToEnd();
    }
}

The JSON.stringify method converts a javascript object into a JSON string and it is a native method built-in modern browsers. You might also need to include json2.js if you want to support older browsers.



来源:https://stackoverflow.com/questions/6421351/post-json-object-array-to-ihttphandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!