我的 asp.net 代码隐藏页面上有以下 web 方法:
[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; }
}
我想弄清楚的是如何调用此 web 方法并格式化我的数据,以便将它正确地投影/解析到该类中,以便我可以使用它。我尝试向该方法发送一个 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"}]
}
最佳答案
按照以下步骤,您将获得所需的输出
Ajax函数调用
function CallAjaxRequest() {
var Simplefailuredata = {};
Simplefailuredata.Id = 1;
Simplefailuredata.Comments = 'Comments-1';
Simplefailuredata.Score = 500.25;
Simplefailuredata.Adjustment = 700.25;
Simplefailuredata.ShutdownData = new Array();
Simplefailuredata.ShutdownData[0] = new Object({ Id: 2, Description: "Desc-1", CausedShutdown: true, ShutdownType: "ShutdownType-1" });
Simplefailuredata.ShutdownData[1] = new Object({ Id: 5, Description: "Desc-2", CausedShutdown: false, ShutdownType: "ShutdownType-2" });
var object = JSON.stringify({ simplefailuredata: Simplefailuredata });
$.ajax({
type: "POST",
url: "Default2.aspx/GetResponse",
contentType: 'application/json; charset=utf-8',
data: object,
dataType: 'json',
cache: false
});
}
<form id="form1" runat="server">
<div>
<input type="button" id="btn" value ="t" onclick="CallAjaxRequest();" />
</div>
</form>
代码隐藏
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string GetResponse(simplefailuredata simplefailuredata)
{
return "";
}
}
public class simplefailuredata
{
public int Id;
public string Comments;
public double Score;
public double Adjustment;
public List<shutdownData> ShutdownData;
}
public class shutdownData
{
public int Id { get; set; }
public string Description { get; set; }
public bool CausedShutdown { get; set; }
public string ShutdownType { get; set; }
}
关于asp.net - 如何为采用类参数的asp.net webmethod格式化JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21023259/