使用asp.net中的Jquery / JSON在aspx页面上显示数据表

时间:2014-03-01 10:42:45

标签: c# javascript jquery asp.net jqgrid

我想在我的ajax帖子中绑定一个数据表。

我正在尝试的代码

在我的cs页面

public static DataTable GetTable()
    {
        //
        // Here we create a DataTable with four columns.
        //
        DataTable table = new DataTable();
        table.Columns.Add("UserId", typeof(int));
        table.Columns.Add("UserName", typeof(string));
        table.Columns.Add("Location", typeof(string));

        //
        // Here we add five DataRows.
        //
        table.Rows.Add(25, "Indocin", "David");
        table.Rows.Add(50, "Enebrel", "Sam");
        table.Rows.Add(10, "Hydralazine", "Christoff");
        table.Rows.Add(21, "Combivent", "Janet");
        table.Rows.Add(100, "Dilantin", "Melanie");
        return table ;
    }

在Aspx页面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 id="Head1" runat="server">
    <title>Asp.net Bind Data to Datatable using JQuery or JSON</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            debugger;
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Default.aspx/GetTable",
                data: "{}",
                dataType: "json",
                success: function(data) {
                for (var i = 0; i < data.d.length; i++) {
                        debugger;
                        $("#tbDetails").append("<tr><td>" + data.d[i].UserId + "</td><td>" + data.d[i].UserName + "</td><td>" + data.d[i].Location + "</td></tr>");
                    }
                },
                error: function(result) {
                    alert("Error");
                }
            });
        });
    </script>

    <style type="text/css">
        table, th, td
        {
            border: 1px solid black;
            border-collapse: collapse;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <table id="tbDetails" cellpadding="0" cellspacing="0">
        <thead style="background-color: #DC5807; color: White; font-weight: bold">
            <tr style="border: solid 1px #000000">
                <td>
                    UserId
                </td>
                <td>
                    UserName
                </td>
                <td>
                    Location
                </td>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    </form>
</body>
</html>

不知道为什么它不起作用..

0 个答案:

没有答案