c# 数据源转Json格式

本文介绍了一种使用C#和JavaScript实现前后端数据交互的方法,通过点击按钮,后台动态加载数据源,并将数据绑定到前端下拉框中。具体实现包括:前端使用jQuery发送请求并解析返回的JSON数据,后台使用ASP.NET处理请求并返回JSON格式的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

前台:

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

 

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

转载于:https://www.cnblogs.com/xinjian/archive/2010/11/23/1885225.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值