此示例展示通过 AjaxPro 返回一个 DataSet 并在页面上通过 html table 输出。
主要代码
// js
<script type="text/javascript"> function GetProductData() { var cb = function(res) { if(res.error) return alert("发生错误\n" + res.error.Message); //debugger; //alert(res); var ds = res.value; var tbl = ds.Tables[0]; var tblHtml = "<table border=1>"; // 表头 tblHtml += "<tr>"; for(var j = 0; j < tbl.Columns.length; j++) { tblHtml += "<th>" + tbl.Columns[j].Name + "</th>"; } tblHtml += "</tr>"; // 数据 for(var i = 0; i < tbl.Rows.length; i++) { tblHtml += "<tr>"; for(var j = 0; j < tbl.Columns.length; j++) { tblHtml += "<td>" + tbl.Rows[i][tbl.Columns[j].Name] + "</td>"; } tblHtml += "</tr>"; } tblHtml += "</table>"; var divPro = document.getElementById("divPro"); divPro.innerHTML = tblHtml; } AjaxProSample.GetProductSet(cb); } </script>
.aspx.cs
[AjaxPro.AjaxNamespace("AjaxProSample")]
public partial class AjaxPro_ReturnDataSet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(AjaxPro_ReturnDataSet));
}
[AjaxPro.AjaxMethod]
public static DataSet GetProductSet()
{
return CreateSampleProductSet();
}
#region sample data
static DataSet CreateSampleProductSet()
{
DataSet ds = new DataSet();
ds.Tables.Add(CreateSampleProductData());
return ds;
}
static DataTable CreateSampleProductData()
{
DataTable tbl = new DataTable("Products");
tbl.Columns.Add("ProductID", typeof(int));
tbl.Columns.Add("ProductName", typeof(string));
tbl.Columns.Add("UnitPrice", typeof(decimal));
tbl.Columns.Add("CategoryID", typeof(int));
tbl.Rows.Add(1, "Chai", 18, 1);
tbl.Rows.Add(2, "Chang", 19, 1);
tbl.Rows.Add(3, "Aniseed Syrup", 10, 2);
tbl.Rows.Add(4, "Chef Anton's Cajun Seasoning", 22, 2);
tbl.Rows.Add(5, "Chef Anton's Gumbo Mix", 21.35, 2);
tbl.Rows.Add(47, "Zaanse koeken", 9.5, 3);
tbl.Rows.Add(48, "Chocolade", 12.75, 3);
tbl.Rows.Add(49, "Maxilaku", 20, 3);
return tbl;
}
#endregion
}
AjaxPro 支持直接返回 DataTable 和 DataView ,客户端读取方式同 DataSet
var tbl = res.value; // 直接访问 DataTable
需要注意的是,返回 DataView,实际上是返回 DataView 关联的 DataTable 。
浙公网安备 33010602011771号