开发者

How do I send JSON to Asp.NET Webservice?

I have a javascript object that I am serializing using JSON2 library. I am then trying to pass this JSON string to a ASP.net webservice. I have changed the webmethod to try several different parameter configurations but they all result in a '500 - Internal Server Error'

Can someone give me a clue?

 function postDataToService(data) {
    $.ajax({
        url: "http://localhost:2686/DataCollectionService.asmx/StoreDataOut",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: data,
        success: showSuccessNotice,
        error: showFailureNotice,
        dataType: "json"
    });

} //postdatatoservice

function convertDataToJSON(jsObj) {

    return JSON.stringify({ list: jsObj });

} //converdatatojson

Web Service:

 [WebService(Namespace = "h开发者_开发知识库ttp://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class DataCollectionService : WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string StoreDataOut(List<string> list)
    {
        return "Complete";
        //model functionality
    }
}


I got it..

Step 1 : I wrapped the JS object in another object that contains a property that matches the parameter name at the web method. Notive the quotes around the

return JSON.stringify({'json':jsObj});

Step 2 I then serialized this new 'wrapper' object with JSON.stringify().

Step 3 Parameter name at web method matched posted json property name. Type is 'object'

 public string StoreDataOut(object json)
    {

    }


I used the code you provided and was able to post to the webservice without issues.

Some questions:

  1. What does data look like?
  2. What is the 500 server error? Can you browse the webservice directly without errors? http://localhost:2686/DataCollectionService.asmx/StoreDataOut
  3. I noticed in your data to send you never call convertDataToJSON() was this a typo? If not perform the ajax post like the following:


   $.ajax({
            url: "http://localhost:2686/DataCollectionService.asmx/StoreDataOut",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: convertDataToJSON(data),
            success: showSuccessNotice,
            error: showFailureNotice,
            dataType: "json"
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜