通过JSON.Net和C#将JSON作为字符串传递回Parse

时间:2014-03-01 09:32:44

标签: c# javascript jquery ajax json.net

我的javascript / jquery前端是这样的:

var jsonData = JSON.stringify({
            'myType': 'typeOfFile',
            tmyData:
            {
                'SelectedYears': myArray["SelectedYears"],
                'columns': myArray["Columns"],
                'rows': myArray["Rows"],
                'filters': myArray["Filters"]
            }
        });

        alert(jsonData);

        $.ajax({
            type: "POST",
            url: "mywebservice.asmx/Create",
            data: jsonData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (xhr, status, error) {
                //alert the error if needed
                //$("#result").html("Sorry there is an error: "   xhr.responseText);
                alert('Error: ' + xhr.responseText);
            },
            success: function (responseData) {
                alert(responseData);
                // show the response data from webservice. Note: the d represent the object property data passed by webservice. It can an object of properties or just single property
                //$("#result").html("The id is " + responseData.d.ID + " And Name is " + responseData.d.Name + " And Email is " + responseData.d.Email);
            }
        });

我的webservice.asmx文件:

[WebService(Namespace = "http://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 mywebservice : System.Web.Services.WebService
{

    [WebMethod]
    public string Create(string myType, string myData)
    {
        //JToken token = JObject.Parse(myData.ToString());

        //JObject obj = (JObject)token.SelectToken("SelectedYears");

        return "Hello World";
    }
}

上面的内容崩溃了,因为我想要的第二个参数是一个字符串,但它不被接受。如果我将其更改为对象,它可以工作。如何将其添加到字符串中以便我可以使用JSON.Net来解析它?

1 个答案:

答案 0 :(得分:0)

我必须说我没有尝试过,但我的猜测是你必须将myData的类型更改为匹配的对象,因为你的js对象不是字符串。

例如:

class MyData
{
   // Whatever are your properties ex: SelectedYears, columns etc..
}

将签名更改为

public string Create(string myType, MyData myData)