DataTable转JSON到前台

来源:互联网 发布:最简单的游戏c编程 编辑:程序博客网 时间:2024/05/29 09:16

环境准备:

JQuery插件,VS环境,C# Newtonsoft  (JSON工具)

后台代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using Newtonsoft;namespace MongoDBTest{    public partial class Default2 : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)      {          if (Request["action"] == "getJson")              BuilderJson();      }        private void BuilderJson()      {        Model.jsonModel js = new Model.jsonModel();        js.QuestionID1 = 12;               DataTable dt = new DataTable();        DataColumn row = new DataColumn();        dt.Columns.Add(new DataColumn("QuestionID1"));  //要注意这里的  QuestionID1对应前台的属性                              for (int i = 0; i < 4; i++)        {            dt.Rows.Add(js.QuestionID1);        }               string json = Newtonsoft.Json.JsonConvert.SerializeObject(dt); //使用json工具类的对象转为JSON               Response.Write(json);        Response.End();      }              }}

前台代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default2.aspx.cs" Inherits="MongoDBTest.Default2" %><!DOCTYPE html>  <html xmlns="http://www.w3.org/1999/xhtml">  <head id="Head1" runat="server">      <title>无标题页</title>      <%--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> --%>     <script src="JS/jquery-1.8.3.min.js"></script>    <script type="text/javascript">        $(function () {            $.getJSON("Default2.aspx?action=getJson", function (json) {                var trArr = [];                trArr.push("<div><strong>一、多选题</strong></div>");                var trBrr = ["<div><strong>二、选择题</strong></div>"];                $(json).each(function (index, value) {                    trArr.push(value.QuestionID1);                });                $("#tbodyList").html(trArr.join("") );            });        });    </script>  </head>  <body>      <form id="form1" runat="server">      <div id="tbodyList">         <%-- <table style="width:200px;" border="1">              <thead><tr><td>题号</td><td>题干内容</td></tr></thead>              <tbody id="tbodyList" ></tbody>          </table>  --%>            </div>          <div><input value="提交" type="button"  /></div>    </form>  </body> </html>  


0 0
原创粉丝点击