且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JQuery Ajax调用Asp.net Web方法

更新时间:2023-02-15 22:06:45

有关返回什么一个数据表

What about returning even a datatable

 $.ajax({
type: "POST",
url: "YourPage.aspx/doSomething",
data: "{'id':'1'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
    var returnedstring = data.d;
    var jsondata = $.parseJSON(data.d);//if you want your data in json
  }
});

ASPX:

aspx:

[WebMethod]
public static string doSomething(int id)
{
   ....
   DataTable dt = new DataTable();
   dt = anothermethodReturningdt(id)

   return JsonConvert.SerializeObject(dt);
}

您可以使用 json.net 序列化.NET对象。

You can use json.net for serializing .Net objects

修改

您也可以做到这一点。

[WebMethod]
public static string doSomething(int id)
{
   Product product = new Product();
   product.Name = "Apple";
   product.Expiry = new DateTime(2008, 12, 28);
   product.Price = 3.99M;
   product.Sizes = new string[] { "Small", "Medium", "Large" };

   return JsonConvert.SerializeObject(product);
}

问题的关键是,你可以序列化任何类型的对象,数组,集合等,然后将它传递回调用脚本。

The point is you can serialize any type of object, arrays, collections etc and then pass it back to the calling script.