http://www.cnblogs.com/Mac_Hui/archive/2010/07/27/1785864.html
1、首先建立以个.ashx文件(Generic Handler),在此文件中生成JSON数据。
using System;
using System.Web;
using System.Data;
using System.Text; public class EmployeeLoad : IHttpHandler { public void ProcessRequest (HttpContext context) { StringBuilder sb = new StringBuilder();
DataTable dt = new DataTable();
dt = FetchEmployeeInfo().Tables[];
if (dt == null)
return;
if (dt.Rows.Count == )
{
return;
}
else
{
sb.Append("[");
for(int i=;i<dt.Rows.Count;i++)
{
sb.Append("{\"ID\":\"" + dt.Rows[i]["ID"].ToString() + "\",\"Name\":\"" + dt.Rows[i]["Name"].ToString() + "\",\"Age\":" + dt.Rows[i]["Age"].ToString() + ",\"Tel\":\"" + dt.Rows[i]["Tel"].ToString() + "\"},");
} sb.Remove(sb.Length - , );
sb.Append("]");
} context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(sb.ToString());
} public bool IsReusable {
get {
return false;
}
} public DataSet FetchEmployeeInfo()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("Tel", typeof(string)); //DataRow dr; DataRow dr = dt.NewRow();
dr["ID"] = "";
dr["Name"] = "Jim Hui";
dr["Age"] = ;
dr["Tel"] = "";
dt.Rows.Add(dr); dr = dt.NewRow();
dr["ID"] = "";
dr["Name"] = "Kevin Lee";
dr["Age"] = ;
dr["Tel"] = "";
dt.Rows.Add(dr); ds.Tables.Add(dt);
return ds; } }
2、其次在前台调用ashx文件中生成的数据
<script type="text/javascript" src="JavaScript/jquery-1.3.2.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
BindDropDownList();
});
function BindDropDownList()
{
$("#DropDownList1").html("");
$.getJSON("EmployeeLoad.ashx",null,function(json){
$.each(json,function(i){$("#DropDownList1").append($("<option></option>").val(json[i].ID).html(json[i].Name))});
});
$("<option></option>").val("").html("").appendTo("#DropDownList1"); }
</script>
这样就OK了。
注意:
1、要调试ashx代码,需要安装VS2005 SP1,即使有sp2也不可以的。
2、Dropdownlist增加空白选项是:$("<option></option>").val("").html("").appendTo("#DropDownList1");