.Net中Ajax复杂数据交互处理

Person对象

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Address { get; set; }
  public string City { get; set; }
  public string State { get; set; }
  public string Zip { get; set; }
 
  public void Add()
  {
    // Magic happens here.
  }
}

页面元素

<label for="FirstName">First Name:</label>
<input type="text" id="FirstName" />
<label for="LastName">Last Name:</label>
<input type="text" id="LastName" />
<label for="Address">Address:</label>
<input type="text" id="Address" />
<label for="City">City:</label>
<input type="text" id="City" />
<label for="State">State:</label>
<input type="text" id="State" />
<label for="Zip">Zip:</label>
<input type="text" id="Zip" />
<input type="button" id="Save" value="Save" />

方法1(笨方法)

[WebMethod]
public void AddPerson(string FirstName, string LastName, 
                      string Address, string City,
                      string State, string Zip)
{
  Person newPerson = new Person();
 
  newPerson.FirstName = FirstName;
  newPerson.LastName = LastName;
  newPerson.Address = Address;
  newPerson.City = City;
  newPerson.State = State;
  newPerson.Zip = Zip;
 
  newPerson.Add();
}
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: "{'FirstName':'" + $("#FirstName").val() + "', "
       + "'LastName':'" + $("#LastName").val() + "',"
       + "'Address':'" + $("#Address").val() + "',"
       + "'City':'" + $("#City").val() + "',"
       + "'State':'" + $("#State").val() + "',"
       + "'Zip':'" + $("#Zip").val() + "'}",
  dataType: "json"
});

方法2(稍微好点)

[WebMethod]
public void AddPerson(Person NewPerson)
{
  NewPerson.Add();
}
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: "{'NewPerson': {'FirstName':'" + $("#FirstName").val() + "',"
                     + "'LastName':'" + $("#LastName").val() + "',"
                     + "'Address':'" + $("#Address").val() + "',"
                     + "'City':'" + $("#City").val() + "',"
                     + "'State':'" + $("#State").val() + "',"
                     + "'Zip':'" + $("#Zip").val() + "'}}",
  dataType: "json"
});

方法3(Better)

[WebMethod]
public void AddPerson(Person NewPerson)
{
  NewPerson.Add();
}
// Initialize the object, before adding data to it.
var NewPerson = new Object();
 
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
 
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: "{'NewPerson':" + JSON.stringify(NewPerson) + "}",
  dataType: "json"
});
JSON.stringify() 在IE6, IE7中不支持,可以用以下方法:
// JSON转换为字符串
    function JSONstringify(Json) {
        if ($.browser.msie) {
            if ($.browser.version == "7.0" || $.browser.version == "6.0") {
                var result = jQuery.parseJSON(Json);
            } else {
                var result = JSON.stringify(Json);
            }
        } else {
            var result = JSON.stringify(Json);
        }
        return result;
    }

方法4 最少的代码,推荐

// Initialize the object, before adding data to it.
//  { } is declarative shorthand for new Object().
var NewPerson = { };
 
// Iterate over all the text fields and build an
//  object with their values as named properties.
$(':text').each(function() {
  // Ex: NewPerson['FirstName'] = $('#FirstName').val();
  NewPerson[this.id] = this.value;
});
 
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewPerson' : NewPerson };
 
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: JSON.stringify(DTO),
  dataType: "json"
});

需注意的是:ajax的参数对象名一定要跟Server端的一致,如:ajax端用的:NewPerson, Server端的方法:public void AddPersson(Person NewPerson)

如果不一致,在调用的时候会报500错误。

若客户端传的是Json字符串,也可以通过以下方法:

{"PersonToSave":"{\"FirstName\":\"Dave\",\"LastName\":\"Ward\"}"}
[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public void SavePerson(string PersonToSave)
  {
    JavaScriptSerializer jss = new JavaScriptSerializer();
 
    Person p = jss.Deserialize<Person>(PersonToSave);
 
    p.Save();
  }
}

参考:

http://www.cnblogs.com/xiaowu/archive/2011/09/07/2169283.html

http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/

http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

转载于:https://www.cnblogs.com/muskteer/archive/2013/03/18/2965856.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值