我收到错误绑定数据与jquery数据表

时间:2017-04-20 11:04:12

标签: c# jquery sql-server json

我想在asp.net中使用jQuery数据表绑定数据库数据,为此我编写了代码。但是在这里我将以JSON格式获取数据到aspx页面。

为什么我无法将数据绑定到jQuery数据表?

CS Code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Script.Serialization;

public partial class Example_JqueryDataTable : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                GetState();
            }
        }

        //Getting all state
        [WebMethod]
        public void GetState()
        {
            string cs = 
          ConfigurationManager.ConnectionStrings["conString2"].ConnectionString;
            List<State> stateList = new List<State>();
            using(SqlConnection con=new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("SELECT StateId,StateName,IsUnionTerritory FROM State_Master ORDER BY StateName ASC", con);
                //cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    State objState = new State();
                    objState.StateId = Convert.ToInt32(dr["StateId"]);
                    objState.StateName = dr["StateName"].ToString();
                    objState.IsUnionTerritory = Convert.ToBoolean(dr["IsUnionTerritory"]);
                    stateList.Add(objState);
                }
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(stateList));
        }
    // Properties
        public class State
        {
            public int StateId { get; set; }
            public string StateName { get; set; }
            public bool IsUnionTerritory { get; set; }
        }
}

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

<!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>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
  <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: 'JqueryDataTable.aspx/GetState',
                method: 'post',
                dataType: 'json',
                success: function (data) {
                    $('#tblState').DataTable({
                        data: data,
                        sort: true,
                        searching: true,
                        columns: [
                    { 'data': 'StateId' },
                    { 'data': 'StateName' },
                    { 'data': 'IsUnionTerritory' }
                    ]
                    });
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="container">
        <div class="row col-lg-6">
            <div style="border: 1px solid black; padding: 3px; width: 1200px">
                <table id="tblState" class="table table-bordered">
                    <thead>
                        <tr>
                            <th>
                                State Id
                            </th>
                            <th>
                                State Name
                            </th>
                            <th>
                                Status
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <th>
                                State Id
                            </th>
                            <th>
                                State Name
                            </th>
                            <th>
                                Status
                            </th>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    </form>
</body>
</html>

我附上了我的问题的图像。

Image Link

4 个答案:

答案 0 :(得分:0)

试试这个:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            url: 'JqueryDataTable.aspx/GetState',
            method: 'post',
            dataType: 'json',
            success: function (response) {
                var data = JSON.parse(response);
                $('#tblState').DataTable({
                    data: data,
                    sort: true,
                    searching: true,
                    columns: [
                { 'data': 'StateId' },
                { 'data': 'StateName' },
                { 'data': 'IsUnionTerritory' }
                ]
                });
            }
        });
    });
</script>

答案 1 :(得分:0)

请按以下方式尝试执行ajax post方法:

$(document).ready(function () {       
    BindStateListTable();
});

function BindStateListTable() {
    $("#tblState").DataTable({
        "processing": false,    
        "serverSide": true, 
        "ajax": {
            url: "JqueryDataTable.aspx/GetState",
            type: "post"
        },   
        "columns": [
            { 'data': 'StateId' },
            { 'data': 'StateName' },
            { 'data': 'IsUnionTerritory' }
        ]
    });
}

答案 2 :(得分:0)

GetState方法需要返回一串数据。您可以按如下方式返回stateList对象。

   [WebMethod]
    public string GetState() // string instead of void
    {
        string cs = 
      ConfigurationManager.ConnectionStrings["conString2"].ConnectionString;
        List<State> stateList = new List<State>();
        using(SqlConnection con=new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("SELECT StateId,StateName,IsUnionTerritory FROM State_Master ORDER BY StateName ASC", con);
            //cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                State objState = new State();
                objState.StateId = Convert.ToInt32(dr["StateId"]);
                objState.StateName = dr["StateName"].ToString();
                objState.IsUnionTerritory = Convert.ToBoolean(dr["IsUnionTerritory"]);
                stateList.Add(objState);
            }
        }
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Serialize(stateList); // return your list
    }

答案 3 :(得分:0)

Jquery :

 <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: 'JqueryDataTable.aspx/GetState',
                contentType: 'application/json; charset=utf-8',
                method: 'POST',
                dataType: 'JSON',
                success: function (data) {
                    $('#tblState').DataTable({
                        data: jQuery.parseJSON(data.d),
                        sort: true,
                        searching: true,
                        columns: [
                    { 'data': 'StateId' },
                    { 'data': 'StateName' },
                    { 'data': 'IsUnionTerritory' }
                    ]
                    });
                }
            });
        });
    </script>
CS:

[WebMethod]
    public static string GetState()
    {
        string cs = ConfigurationManager.ConnectionStrings["conString2"].ConnectionString;
        List<State> stateList = new List<State>();
        using(SqlConnection con=new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("SELECT StateId,StateName,IsUnionTerritory FROM State_Master ORDER BY StateName ASC", con);
            cmd.CommandType = CommandType.Text;
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                State objState = new State();
                objState.StateId = Convert.ToInt32(dr["StateId"]);
                objState.StateName = dr["StateName"].ToString();
                objState.IsUnionTerritory = Convert.ToBoolean(dr["IsUnionTerritory"]);
                stateList.Add(objState);
            }
        }
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Serialize(stateList);
    }

    public class State
    {
        public int StateId { get; set; }
        public string StateName { get; set; }
        public bool IsUnionTerritory { get; set; }
    }