嗨,
任何人都知道我在这里做错了什么。我试图
使用 jQuery AJAX 将 JSON 对象发布到 ASP.Net WebMethod。
虽然我在服务器端获取对象,但不是我的方式
通缉。我希望客户对象是一个简单的对象,这样我就可以像普通实例一样访问,例如customer.Name,但我不能,因为它作为字典对象到达那里。
编辑::为什么 JSON 在服务器端作为 C# 动态类型的字典对象?
这是快速观看的截屏;
这是 JavaScript 和服务器端代码。
function SaveCustomer() {
var funcParams = JSON.stringify({
customer: {
Name: "Name of Customer",
Title: "President"
},
address: {
Street: "Street",
City: "",
Zip: ""
}
});
//我尝试使用以下 json 参数,但结果仍然相同。
var funcParams = "{\"customer\":" + JSON.stringify({ Name: "Name of
Customer", Title: "President" }) + ",\"address\":" +
JSON.stringify({ Street: "Street", City: "", Zip: "" }) + "}";
}
$.ajax({ type: "POST", contentType: "application/json; charset=utf-8",
dataType: "json", url: "aspxPage.aspx/SaveCustomer", data: funcParams,
success: function(){ }, error: function(e){alert("Error occured"+e);}
})
[WebMethod(EnableSession = true)]
public static string SaveCustomer(dynamic customer, dynamic address)
{
if(!string.IsNullOrEmpty(customer.Name) &&
!string.IsNullOrEmpty(customer.Title)....)
{
//app logic
}
}
最佳答案
我最近刚刚处理过这种情况。如果您像我一样决定不创建 DTO 类,那么这是我的解决方案。
1) 将序列化的 JSON 字符串传递给 WebMethod
$.ajax({ type: "POST", contentType: "application/json; charset=utf-8",
dataType: "json", url: "aspxPage.aspx/SaveCustomer", data: "{data: '" + funcParams + "'}",
success: function(){ }, error: function(e){alert("Error occured"+e);}
})
2) 使用 JSON.NET 反序列化字符串,然后就可以开始了。
[WebMethod(EnableSession = true)]
public static string SaveCustomer(string data)
{
dynamic customer = JsonConvert.DeserializeObject(data);
customer.Name;
customer.Address;
.....
}
关于asp.net - 具有动态数据类型的 jQuery AJAX POST 对象到 ASP.Net WebMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31346131/