学习了点东西。留个脚印。
实现效果,点击按钮,后台加载数据源,前台绑定到下拉框。
前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JsonTrans.aspx.cs" Inherits="auotoCompleteText.JsonTrans" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script type="text/javascript" src="jquery-1.3.2-vsdoc2.js"></script>
<script type="text/javascript">
function loadValue() {
$.get("JsonTransHander.ashx", function(jsonData) {
debugger;
var json = eval(jsonData);
for (var i = 0; i < json.length; i++) {
//js
//var op = new Option(json[i].Name, json[i].ID);
//document.getElementById("Select1").options.add(op);
//jquery
$("#Select1").append("<option value='" + json[i].value + "'>" + json[i].Name + "</option>");
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="Select1">
</select>
<input type="button" value="Load" onclick="loadValue();" />
</div>
</form>
</body>
</html>
后台:
新建一个一般处理程序,命名为JsonTransHander.ashx。内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
namespace auotoCompleteText
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class JsonTransHander : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//初始化数据
List<People> peopleList = new List<People>();
for (int i = 0; i < 10; i++)
{
People people = new People() { ID=i,Name="name"+i};
peopleList.Add(people);
}
//引用System.Web.Extensions .net3.5框架
JavaScriptSerializer serializer=new JavaScriptSerializer();
//转换
var jsonData= serializer.Serialize(peopleList);
//返回
context.Response.Write(jsonData);
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class People
{
public string Name
{
set;
get;
}
public int ID
{
set;
get;
}
}
}
效果:一个空的下拉框,点击旁边的按钮后,下拉框绑定后台数据。