C# WebMethod - 发送和接收与参数相同的自定义对象
C# WebMethod - Send and receive same custom object as parameter
mycode:
对象:
public class Person
{
private string _Nome;
private DateTime _Nascimento;
public string Nome { get { return _Nome; } }
public DateTime Nascimento { get { return _Nascimento; } }
public Person(string Nome, DateTime Nascimento)
{
_Nome = Nome;
_Nascimento = Nascimento;
}
}
页面(网络方法):
[WebMethod]
public static Person SendPerson()
{
return new Person("Jhon Snow", DateTime.Now);
}
[WebMethod]
public static string ReceivePerson(Person oPerson)
{
return "OK!";
}
JavaScript:
var Person;
GetPerson();
SendPersonBack();
function GetPerson()
{
$.ajax({
type: "POST",
url: "frmVenda.aspx/SendPerson",
data: {},
contentType: "application/json; charset=utf-8",
success: function (RequestReturn) {
Person = RequestReturn.d;
console.log(Person);
},
error: function (error) {
alert(error.statusText);
}
});
}
function SendPersonBack()
{
$.ajax({
type: "POST",
url: "frmVenda.aspx/ReceivePerson",
data: JSON.stringify({"oPerson": Person}),
contentType: "application/json; charset=utf-8",
success: function (RequestReturn) {
alert(RequestReturn.d);
},
error: function (error) {
alert(error.statusText);
}
});
}
我正常将对象发送到客户端,但无法将其接收回服务器。如果对象相同,为什么不能接收它以及它们的属性。问题出在哪里?
查看您提供的链接可能会注意到问题。
您的代码:data: JSON.stringify({"oPerson": Person}),
正确的代码:数据:"{oPerson:" + JSON.stringify(Person) + "}",
在我看来,您正在向服务器发送格式错误的 Json
此外,请尝试将dataType: 'json'
添加到通话中。
我通过创建一个没有参数的构造函数,将所有属性设置为字符串并在自定义对象(Person)上的所有属性上添加set方法解决了这个问题。
public class Person
{
private string _Nome;
private string _Nascimento;
public string Nome { get { return _Nome; } set { _Nome = value; } }
public string Nascimento { get { return _Nascimento; } set { _Nascimento= value; } }
public Person()
{
}
public Person(string Nome, DateTime Nascimento)
{
_Nome = Nome;
_Nascimento = Nascimento.ToString();
}
}
您正在从 webService 返回一个对象,但您在 ajax 中的内容类型是 json!您应该在两种方法中创建 json 格式的数据,并返回一个字符串 not object:
[WebMethod]
public static static SendPerson()
{
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
return TheSerializer.Serialize(new Person("Jhon Snow", DateTime.Now));
}
对于第二种方法,只需从ajax中删除内容类型或将其替换为:
application/x-www-form-urlencoded; charset=UTF-8
相关文章:
- 我们可以用参数对象集合而不是原始数据来调用JavaScript collection.reduce()方法吗
- 如何将参数对象传输到函数
- 为什么参数对象没有在控制台中显示它的方法
- JavaScript参数对象不起作用
- 如何在 JavaScript 中取消移位或添加到参数对象的开头
- 使用参数对象而不是参数
- JavaScript 参数对象 MDN 指南
- 如何获取参数对象的子集?(关于具有可变大小的参数)
- 如何更好地检查 javascript 中的参数对象
- 如何使用 ajax 调用带有参数(对象)的服务器端方法,其中 url 具有查询参数
- 如何在 ie8 中检测参数对象
- 手动将 AngularJS $http参数对象转换为 URL 参数
- JavaScript 参数对象引用未知
- Javascript - 对 2 参数对象的数组进行排序
- 为什么下划线说 _.initial 对参数对象特别有用
- 未命名的传递参数不包含在“参数”对象中
- JavaScript:获取回调的参数对象
- Javascript参数对象
- 围绕JavaScript参数对象使用的Sonar违规
- each()在IE8上不起作用,并给了我一个“;期望应用数组或参数对象”;.如何解决