zoukankan      html  css  js  c++  java
  • c# 数据源转Json格式

    学习了点东西。留个脚印。

    实现效果,点击按钮,后台加载数据源,前台绑定到下拉框。

    前台:

    <%@ 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;
    }
    }
    }

    效果:一个空的下拉框,点击旁边的按钮后,下拉框绑定后台数据。

  • 相关阅读:
    java Future 模式
    多线程的优点和代价
    转:Java同步synchronized使用
    管程
    【移动开发人员沙龙 北京站】第二期 报名火热来袭
    POJ 3111 K Best(最大化平均值)
    坐标和依赖
    分析cocos2d-x在Android上的编译过程(1):cocco2d-x是怎样生成的Android的文件夹结构
    执行startx后Ubuntupassword正确进不去的问题
    leetcode 刷题之路 64 Construct Binary Tree from Inorder and Postorder Traversal
  • 原文地址:https://www.cnblogs.com/xinjian/p/1885225.html
Copyright © 2011-2022 走看看