ASP.NET数据转成json / Ajax取出json作为下拉框数据源

1.目的:把ASP.NET数据转成json格式,异步取得该json格式的字符串,把json作为下拉框<select>标签的数据源。

2.前台页面:AddSalesOrder.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="../JavaScript/jquery-1.7.2.min.js"></script>
    <title>创建销售订单</title>
    <style type="text/css">
        .input {
            width: 190px;
        }
    </style>

    <script type="text/javascript">

        $(document).ready(function () { //页面加载完毕即执行,利用ajax取回数据填充到各个下拉框中
            getGSdata();
        });

        function getGSdata() { //利用ajax异步获取来自一般处理程序的数据
           $.ajax({
                type: "post",
                url: "../Ajax/AddHandler.ashx",
                data: "sign=1",
                success: function(jsonData){
                    var json = eval(jsonData);            
                    for (var i = 0; i < json.length; i++) {
               $("#gs").append("<option value='"+json[i].value + "'>" + json[i].text + "</option>");
                    }
                }
            }
            );
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         公司: <select id="gs" class="input"></select>        
 
    </div>
    </form>
</body>
</html>


3.后台即一般处理程序:AddHandler.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace UEP.SalesOrder.Web.Ajax
{
    /// <summary>
    /// AddHandler 的摘要说明
    /// </summary>
    public class AddHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            
            int sign;
            string result="";
            sign = Convert.ToInt32(context.Request.Form["sign"]);
            switch (sign)
            {
                case 1: result = loadGS();
                    context.Response.Write(result);
                    break;
                
            }
            
        }

        public string loadGS()
        {
            List<GS> gsList = new List<GS>();
            for (int i = 0; i < 5; i++)
            {
                GS gs = new GS() { value = i,text = "公司" + i };
                gsList.Add(gs);
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var jsonData = serializer.Serialize(gsList);

            return jsonData;
        }

        public class GS //公司类
        {
           public  int  value { get; set; }
           public  string text { get; set; }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


4.运行结果



展开阅读全文

没有更多推荐了,返回首页