jQuery DataTables 服务器端处理和ASP.Net

10

我正在尝试在ASP.Net中使用jQuery Datatables插件的服务器端功能。Ajax请求返回有效的JSON,但是表格中没有显示任何内容。

最初我在发送Ajax请求时遇到了一些问题。我收到了一个"Invalid JSON primitive"错误。我发现数据需要以字符串而不是JSON序列化形式发送,如此帖子所述:http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/。我不太确定如何修复它,所以我尝试在Ajax请求中添加了这个:

"data": "{'sEcho': '" + aoData.sEcho + "'}"

如果上述方法最终生效,我将稍后添加其他参数。目前我只是想让某些内容显示在我的表格中。

返回的JSON看起来不错并且验证通过,但是post中的sEcho未定义,我认为这就是为什么没有数据加载到表格中的原因。

那么,我做错了什么?我是否走错了路或者很傻?有人之前遇到过这个问题或者有任何建议吗?

以下是我的jQuery代码:

$(document).ready(function()
{

    $("#grid").dataTable({
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "bServerSide":true, 
            "sAjaxSource": "GridTest.asmx/ServerSideTest", 
            "fnServerData": function(sSource, aoData, fnCallback) {
               $.ajax({
                    "type": "POST",
                    "dataType": 'json',
                    "contentType": "application/json; charset=utf-8",
                    "url": sSource, 
                    "data": "{'sEcho': '" + aoData.sEcho + "'}",
                    "success": fnCallback
                });
           }
         });


 });

HTML:

<table id="grid">
   <thead>
      <tr>
         <th>Last Name</th>
         <th>First Name</th>
         <th>UserID</th>
       </tr>
    </thead>

    <tbody>
       <tr>
    <td colspan="5" class="dataTables_empty">Loading data from server</td>
       </tr>
    </tbody>
 </table>

Webmethod:

 <WebMethod()> _
Public Function ServerSideTest() As Data


    Dim list As New List(Of String)
    list.Add("testing")
    list.Add("chad")
    list.Add("testing")

    Dim container As New List(Of List(Of String))
    container.Add(list)

    list = New List(Of String)
    list.Add("testing2")
    list.Add("chad")
    list.Add("testing")

    container.Add(list)

    HttpContext.Current.Response.ContentType = "application/json"

    Return New Data(HttpContext.Current.Request("sEcho"), 2, 2, container)

End Function


Public Class Data
Private _iTotalRecords As Integer
Private _iTotalDisplayRecords As Integer
Private _sEcho As Integer
Private _sColumns As String
Private _aaData As List(Of List(Of String))

Public Property sEcho() As Integer
    Get
        Return _sEcho
    End Get
    Set(ByVal value As Integer)
        _sEcho = value
    End Set
End Property

Public Property iTotalRecords() As Integer
    Get
        Return _iTotalRecords
    End Get
    Set(ByVal value As Integer)
        _iTotalRecords = value
    End Set
End Property

Public Property iTotalDisplayRecords() As Integer
    Get
        Return _iTotalDisplayRecords
    End Get
    Set(ByVal value As Integer)
        _iTotalDisplayRecords = value
    End Set
End Property



Public Property aaData() As List(Of List(Of String))
    Get
        Return _aaData
    End Get
    Set(ByVal value As List(Of List(Of String)))
        _aaData = value
    End Set
End Property

Public Sub New(ByVal sEcho As Integer, ByVal iTotalRecords As Integer, ByVal iTotalDisplayRecords As Integer, ByVal aaData As List(Of List(Of String)))
    If sEcho <> 0 Then Me.sEcho = sEcho
    Me.iTotalRecords = iTotalRecords
    Me.iTotalDisplayRecords = iTotalDisplayRecords
    Me.aaData = aaData
End Sub

返回的 JSON:

{"__type":"Data","sEcho":0,"iTotalRecords":2,"iTotalDisplayRecords":2,"aaData":[["testing","chad","testing"],["testing2","chad","testing"]]}
4个回答

4
我已经将数据更改为:
"data": "{'sEcho': '"+ aoData[0].value + "'}",

它成功了。现在的问题是如何将其余的数据传递给Web服务。我尝试使用JSON2将JSON转换为字符串,但这又引发了另一个问题,这是另一个问题。


3

你的Javascript代码中至少存在两个问题:

  1. "data": "{'sEcho': '" + aoData[0].value + "'}",

Chad 已经指出了这个问题。获取 sEcho 的正确方法如下:

  1. "success": function (msg) { fnCallback(msg.d); }

如果你使用的是较新版本的 .net(我相信3.5及以上版本),你需要调整 success 函数以正确返回。阅读 this 以了解为什么要传递 "msg.d"。

以下是更新后的 Javascript 代码:

$("#grid").dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bServerSide":true, 
        "sAjaxSource": "GridTest.asmx/ServerSideTest", 
        "fnServerData": function(sSource, aoData, fnCallback) {
           $.ajax({
                "type": "POST",
                "dataType": 'json',
                "contentType": "application/json; charset=utf-8",
                "url": sSource, 
                "data": "{'sEcho': '" + aoData[0].value + "'}",
                "success": function (msg) {
                            fnCallback(msg.d);
                        }
            });
       }
     });

然后在服务器端使其工作,我不确定你需要在代码中做出哪些更改(因为我不是VB专业人员),但我知道以下内容对我有效(使用asmx web服务):

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class GridTest : System.Web.Services.WebService
{

    [WebMethod]
    public FormatedList ServerSideTest(string sEcho)
    {
        var list = new FormatedList();

        list.sEcho = sEcho;
        list.iTotalRecords = 1;
        list.iTotalDisplayRecords = 1;

        var item = new List<string>();
        item.Add("Gecko");
        item.Add("Firefox 1.0");
        item.Add("Win 98+ / OSX.2+");
        item.Add("1.7");
        item.Add("A");
        list.aaData = new List<List<string>>();
        list.aaData.Add(item);

        return list;
    }

}

public class FormatedList
{
    public FormatedList()
    {
    }
    public string sEcho { get; set; }
    public int iTotalRecords { get; set; }
    public int iTotalDisplayRecords { get; set; }
    public List<List<string>> aaData { get; set; }
}

"FormatedList" 类仅用于帮助 JSON 返回,因为我们使用 ScriptService 进行自动转换。


2

我一直在做同样的事情,我的一个朋友帮我处理了这部分。这段代码是用C#编写的,但你应该能够移植它。

jQuery代码:

<script type="text/javascript">
        $(document).ready(function() {
            function renderTable(result) {
                var dtData = [];
                // Data tables requires all data to be stuffed into a generic jagged array, so loop through our
                // typed object and create one.
                $.each(result, function() {
                    dtData.push([
                           this.FirstName,
                           this.LastName,
                           this.Sign
                        ]);
                });

                $('#grid').dataTable({
                    'aaData': dtData,
                    "bJQueryUI": true
                });
            }

            // Make an AJAX call to the PageMethod in the codebehind
            $.ajax({
                url: '<%= Request.Url.AbsolutePath %>/ServerSideTest',
                data: '{}',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(result) {
                    // Call the renderTable method that both fills the aaData array with data and initializes the DataTable.
                    renderTable(result.d);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest + ": " + textStatus + ": " + errorThrown);
                }
            });
        });
    </script>

ASPX代码:

<table id="grid" width="100%">
        <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Sign</th>
            </tr>
        </thead>

        <tbody>
            <tr>
                <td colspan="5" class="dataTables_empty">Loading data from server</td>
            </tr>
        </tbody>
    </table>

代码后台:

// to serialize JSON in ASP.NET, it requires a class template.
    [Serializable]
    public class Data
    {
        // Yay for 3.5 auto properties
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Sign { get; set; }
    };

    [WebMethod]
    public static List<Data> ServerSideTest()
    {
        List<Data> DataList = new List<Data>();

        Data thisData = new Data();
        thisData.FirstName = "Sol";
        thisData.LastName = "Hawk";
        thisData.Sign = "Aries";

        DataList.Add(thisData);

        Data thisData2 = new Data();
        thisData2.FirstName = "Mako";
        thisData2.LastName = "Shark";
        thisData2.Sign = "Libra";

        DataList.Add(thisData2);

        return DataList;
    }

我希望这可以帮到你!
接下来我要做的是让筛选、分页和排序功能正常工作。如果你成功实现了这些功能,请告诉我 =)

2

+1 分享与问题相关的链接。我发现这个链接对我的情况非常有帮助。谢谢。 - Moiz Tankiwala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接