• 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;
    }
    }
    }

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

  • 相关阅读:
    AtCoder Regular Contest 066 F Contest with Drinks Hard
    AtCoder Grand Contest 002 D
    AtCoder Regular Contest 076 F
    AtCoder Grand Contest 004 C
    AtCoder Regular Contest 067 F
    转载:Unity3D游戏对象消失enabled、Destroy与active的区别
    Unity3d-AngryBots实例解读
    本类对象的引用作为参数,可以直接访问其私有成员
    构建完全二叉树、控制台打印二叉树
    转载:C++类内存分布
  • 原文地址:https://www.cnblogs.com/xinjian/p/1885225.html
Copyright © 2020-2023  润新知