简体   繁体   中英

ASP.NET / jQuery : post JSON to web-service

I'm trying to post some JSON to a web service. The web-service is executed but there's no data available.

The jQuery looks like this :

var json = {"Results": results};
var jsonArray=JSON.stringify(json);
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: requestURL,
    data: jsonArray ,
    dataType: "json",
    success: function (data) { TCG.QUE.processSaveButtonSucceeded(data); },
    error: function (data) { TCG.QUE.processSaveButtonFailed(data); }
});

And the webservice implemented in a controller looks like this :

public HttpResponseMessage Post([FromBody]string value)
{
    object o1 = Request.Content;
    HttpResponseMessage r = new HttpResponseMessage(HttpStatusCode.OK);
    return r;
}

If I take out the [FromBody] directive then I get a 404. If I leave it in the code is executed but the value of the value argument is null.

I thought the [FromBody] directive meant the data was contained in the Request object but if it is I can't find it .

Would appreciate any suggestions so that I can access the JSON from the client within the Post method.


UPDATE:

I just re-read this : http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api which made me wonder whether the name I was giving the JSON blog client side should correspond to the name of the argument on which the [FromBody] is applied so I changed the name of the argument from value to Results but still the value within the Post method is null.


RESOLUTION After reading the blog post referred to by Prashanth Thurairatnam I changed my method to be like this and it works :

    public HttpResponseMessage Post([FromBody]JToken jsonbody)
    {
        // Process the jsonbody 

        return new HttpResponseMessage(HttpStatusCode.Created);
    }

.

Not sure what you are passing into results . Ran into this blog . You may want to give it a go. The blog talks on passing the data as JSON object/ array (you may want to try without JSON.stringify)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM