【发布时间】:2012-03-09 19:53:32
【问题描述】:
我有一个关于从 JQuery 创建 JSON、通过 Ajax 将其发送到 .NET 中的 Web 服务以及如何在 .NET 中反序列化并保存到数据库的问题。
也许有人可以帮我看看我错在哪里!
jQuery 和 JSON:
var myObject = {};
//** BusinessPartner **
//function BusinessPartner(prefix) {
// this.bpCodigo = $(prefix + " option:selected").val();
// this.bpNombre = $(prefix + "-infonombre").text();
//
//** Locations **
//function Locations(prefix) {
// this.locCode = $(prefix + " option:selected").val();
// this.locName = $(prefix + "-name").text();
var oNewObject = new BusinessPartner("#bp-01");
var oNewObject2 = new BusinessPartner("#bp-02");
var myLocation = [];
var oOrigin = new Locations("#receipt");
myLocation.push(oOrigin);
var oDestination = new Locations("#portloading");
myLocation.push(oOrigin);
myObject["Agent1"] = oNewObject;
myObject["Agent2"] = oNewObject;
myObject["Locations"] = myLocation;
$.ajax({
type: "POST",
url: "Services/ActionsDb.asmx/saveData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(myObject),
datatype: "json",
success: function (response) {
// After correct save send OK message.
},
error: function (xhr, status) {
alert("An error occurred: " + status);
}
});
C# .NET 中的类
据我了解,它的格式应该与网络服务接收到的 JSON 格式完全相同。
public class Agent
{
public string bpCodigo { get; set; }
public string bpNombre { get; set; }
}
public class Location
{
public string locCode { get; set; }
public string locName { get; set; }
}
public class oGet
{
public Agent oCliente { get; set; }
public Agent oCliente2 { get; set; }
public List<Location> oLocations { get; set; }
}
网络服务
好的,现在将要求 WebService ActionsDb.asmx / savedata 将数据保存在 DB 中。
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string saveData(oGet myObject)
{
try
{
string sClienteName = myObject.oCliente.bpNombre.ToString();
return sClienteName.ToString();
}
catch (System.Exception ex)
{
return ex.Message.ToString();
}
}
结果
我得到的错误如下:
POST http://localhost:8869/Services/WebtoolActionsDb.asmx/saveBLData 500 (Internal Server Error)
{"Message":"Service call not valid. Parameter missing: \u0027myObject\u0027.","StackTrace":"
en System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)
en System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
en System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
en System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
【问题讨论】:
-
如果你
JSON.parse(myObject)会发生什么? -
你能把那个错误信息翻译成英文吗?今后也请仅在我们的网站上使用英语。谢谢。
标签: c# javascript json web-services jquery