DataTable转JSON到前台

环境准备:

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 29
    评论
评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值