我在页面后面的asp.net代码上有以下webmethod:
[WebMethod(EnableSession = true)] public static bool SaveFailureData(SimpleFailureData data) { }
SimpleFailureData定义如下:
public class SimpleFailureData { public int Id { get; set; } public string Comments { get; set; } public double Score { get; set; } public double Adjustment { get; set; } public List<ShutdownData> ShutdownData { get; set; } } public class ShutdownData { public int Id { get; set; } public string Description { get; set; } public bool CausedShutdown { get; set; } public string ShutdownType { get; set; } }
我想弄清楚的是如何调用此网络方法并格式化我的数据,以便将其正确投影/解析到该类中,以便我可以使用它。我尝试向该方法发送json字符串,但是我的方法中的断点从未被命中(因此,我认为该方法由于数据格式不正确而无法调用)。
这是我尝试发送然后调用方法的JSON:
json = JSON.stringify( { Comments: comments, Score: score, Adjustment: seAdjustmentValue, ShutdownData: breakdowns //this is an array of shutdown objects }); PageMethods.SaveFailureData(json, function(data) { return; });
但这无法进入我的方法。有关应采用哪种JSON格式的任何提示,以便将类作为参数正确传递,这是正确的?
这是我尝试发送给该方法的JSON:
{ "Comments":"", "Score":66.66666666666667, "Adjustment":0, "ShutdownData":[{"Id":"401","CausedShutdown":true,"ShutdownType":"NORMAL"}] }
好的,试试这个
public static bool SaveFailureData(string sampleFailure) { JavaScriptSerializer s = new JavaScriptSerializer(); SimpleFailureData sdata = s.Deserialize<SimpleFailureData>(sampleFailure); return true; } var json = { "Comments": "", "Score": 66.66666666666667, "Adjustment": 0, "ShutdownData": [{ "Id": "401", "CausedShutdown": true, "ShutdownType": "NORMAL"}] } var data = JSON.stringify(json); $.ajax({ type: "POST", url: 'Default.aspx/SaveFailureData', contentType: 'application/json; charset=utf-8', data: "{'sampleFailure' : '" + data + "'}", // data: data, dataType: 'json', success: function (msg) { alert(msg.d); }, error: function (msg) { alert('Error!'); } }); });
您将在sdata对象中获取数据。