我在asp.net项目中有一个webmethod我想在jquery ajax方法中传递一个listview但我现在怎么不能检测listview的元素并使用它们。下载代码是我的c#code.bt我需要jquery代码
if (ck != null)
{
reqnum[0, 0] = "@RequestingBranchID";
reqnum[0, 1] = ck["BranchID"];
reqnum[1, 0] = "@ProviderBranchID";
reqnum[1, 1] = customer.ToString();
DataTable dt = SqlCommands.FillData(out OutStatus, out OutMessage, "BSD.SW_Boxes_StockOfProviderAndRequestingBranch", CommandType.StoredProcedure, reqnum);
List<DataRow> rows = dt.Rows.Cast<DataRow>().ToList();
int x=rows.Count;
return rows;
}
答案 0 :(得分:0)
好吧,假设你有一个DataTable
,并希望将此DataTable
的结果传递给某些JavaScript,以便使用Ajax
显示结果。所以第一步是我们需要将这些结果转换为JSON格式。你可以使用以下方法::
public string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow dr in dt.Rows) {
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns) {
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
下一步是在JavaScript中解析结果JSON字符串,我想这很容易。您可以查看此问题,了解如何将JSON字符串解析为对象Safely turning a JSON string into an object。如果您想了解更多,请告诉我。
答案 1 :(得分:0)
您可以使用JSON.NET将数据表序列化为JSON。然后使用ajax调用webmethod。
在服务器端,
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetList(int branchID, string customer)
{
// do your code here
reqnum[0, 0] = "@RequestingBranchID";
reqnum[0, 1] = branchID;
reqnum[1, 0] = "@ProviderBranchID";
reqnum[1, 1] = customer;
DataTable dt = SqlCommands.FillData(out OutStatus, out OutMessage, "BSD.SW_Boxes_StockOfProviderAndRequestingBranch", CommandType.StoredProcedure, reqnum);
if(dt!=null)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(dt);
}
else{
//return "[]";
}
}
然后在脚本中调用您的方法并传递方法的参数。
$(function(){});
$('#myButton').click(function() {
$.ajax({
type: "POST",
url: "YourPage.aspx/GetList",
data: "{'branchID':" + branchID + ",'customer':" + customer + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonResult = $.parseJSON(data.d);
// do your client side code here
}
});
});
});
注意:如果您没有使用Web服务/在后面的代码中编写方法,请在您的类之前使用[ScriptService]
装饰器并包含以下命名空间。
using System.Web.Script.Services;
using System.Web.Services;