【问题标题】:DataTables in ASP.net using JSON使用 JSON 的 ASP.net 中的数据表
【发布时间】:2014-02-10 15:30:24
【问题描述】:

在 ASP.net 中使用 JQuery DataTables 并尝试从 C# WebMethod 返回 JSON 数据。

C#方法...

[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Data()
{
    string json = string.Empty;

    using (IDataReader reader = DBUtil.GetReader("data", "data", "pram"))
    {
        if (reader != null)
        {
            DataTable dt = new DataTable();
            dt.Load(reader);
            reader.Close();
            json = JsonHelper.GetJsonFromDataTable(dt);
        }
    }
    return json;   //also tried by adding "{\"aaData\": " + json + "}"
}

工作中......

var source = {};
$.ajax({
    type: 'POST',
    dataType: 'json',
    url: "page.aspx/Data",
    contentType: 'application/json; charset=utf-8',
    cache: false,
    data: {},
    success: function (response) {
        source = $.parseJSON(response.d);
        alert(response.d); // i can see Json formatted data

    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    }
});

不工作.......(甚至没有达到方法断点)

$(".JGrid").dataTable({
    "bJQueryUI": true,
    "sAjaxSource": "../page.aspx/Data", //also tried with var 'source' (declared sbove)
    "aoColumns": [
        { "sTitle": "Col1name", "sWidth": "33%" },
        { "sTitle": "Col2name", "sWidth": "33%" },
        { "sTitle": "Col3name", "sWidth": "33%" }
    ]
});

【问题讨论】:

  • 网址是否正确?在一个例子中,你有page.aspx/Data,在另一个例子中是../page.aspx/Data...
  • 是的,它是正确的。我也试过“page.aspx/Data”
  • 我看到您正在为您的数据发送一个空对象? 'data: {}' 我会在那里发布我的数据
  • 该代码适用于“数据:{}”.. 但 DataTables 无法正常工作

标签: c# jquery asp.net json jquery-datatables


【解决方案1】:
$("#table-tripNote").dataTable({
                "oLanguage": {
                    "sZeroRecords": "No records to display",
                    "sSearch": "Search from all Records"
                },
                "bProcessing": true,
                "bServerSide": true,
                "bDestroy": true,
                "sAjaxSource": "frmTrip.aspx/GetMemberNotesByTrip",
                "sPaginationType": "full_numbers",
                "bDeferRender": true,
                "aoColumns":
                            [
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null
                            ],
                "fnServerData": function (sSource, aoData, fnCallback) {
                    $.ajax({
                        "dataType": 'json',
                        "contentType": "application/json; charset=utf-8",
                        "type": "GET",
                        "url": sSource,
                        "data": aoData,
                        "success":
                                                    function (msg) {

                                                        var json = jQuery.parseJSON(msg.d);
                                                        fnCallback(json);
                                                        $("#table-tripNote").show();
                                                    }
                    });
                }
            });

这对我有用

看看

【讨论】:

  • 谢谢,现在它命中断点并获取数据,在 var aData = _fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ); 处的 jquery.dataTables.js 中仍然出现错误for ( var i=0, iLen=aData.length ; i
  • 能否请您分享您的 C# web 方法。谢谢。
  • 我已在新答案中添加了网络方法,请查看
【解决方案2】:

你好兄弟,将此属性添加到您的数据表中

----"bServerSide": true, 像这样

$(".JGrid").dataTable({
    "bJQueryUI": true,
"bServerSide": true,
    "sAjaxSource": "/page.aspx/Data", //also tried with var 'source' (declared sbove)
    "aoColumns": [
        { "sTitle": "Col1name", "sWidth": "33%" },
        { "sTitle": "Col2name", "sWidth": "33%" },
        { "sTitle": "Col3name", "sWidth": "33%" }
    ]
});

【讨论】:

  • 已添加,但无法正常工作。仍然没有达到方法断点。不过谢谢
  • 将后面的代码替换为 [WebMethod()] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
【解决方案3】:

查看this page。查看“发送到服务器的参数”。我认为 dataTables 期望您的服务器端 webmethod 接受这些值。您可以使用fnServerData(在同一页面上)选项覆盖它发送的内容。这是在数据发送到后端之前调用的,因此您可以控制发送的内容。

这个post 可能有用。

【讨论】:

  • 谢谢。得到了一些关于 fnServerData 的信息。
【解决方案4】:
[WebMethod()]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string GetMemberNotesByTrip(string sEcho, int iDisplayStart, int iDisplayLength)
{

    string rawSearch = HttpContext.Current.Request.Params["sSearch"].Trim();

    var whereClause = string.Empty;

    var filteredWhere = "1=1";

    var wrappedSearch = rawSearch.Trim();
    var Tempsb = new StringBuilder();

    Tempsb.Append("mbrid=" + MemberID);
    if (TripID != 0)
    {
        Tempsb.Append("and trpid=" + TripID);
    }
    else
        Tempsb.Append("and trpid=0");

    if (rawSearch.Length > 0)
    {
        Tempsb.Append("AND ( ISNULL(trpDate,'''') LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR clrFullName LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR clrPhone LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR clrRelationshipToMember LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR trpNote LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR clrOrganization LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR trpIsGrievance LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(")");
    }

    if (Tempsb.Length > 0)
        filteredWhere = Tempsb.ToString();

    string orderByClause = string.Empty;
    orderByClause = "trpDate desc";

    StringBuilder sb = new StringBuilder();
    sb.Append(Convert.ToInt32(HttpContext.Current.Request.Params["iSortCol_0"]));

    sb.Append(" ");

    sb.Append(HttpContext.Current.Request.Params["sSortDir_0"]);

    orderByClause = sb.ToString();

    if (!String.IsNullOrEmpty(orderByClause))
    {
        orderByClause = orderByClause.Replace("0", ", trpDate ");
        orderByClause = orderByClause.Replace("1", ", clrFullName ");
        orderByClause = orderByClause.Replace("2", ", clrPhone ");
        orderByClause = orderByClause.Replace("3", ", clrRelationshipToMember ");
        orderByClause = orderByClause.Replace("4", ", clrOrganization ");
        orderByClause = orderByClause.Replace("5", ", trpIsGrievance ");
        orderByClause = orderByClause.Replace("6", ", trpNote ");

        orderByClause = orderByClause.Remove(0, 1);
    }
    else
    {
        orderByClause = "pronID ASC";
    }

    DataSet ds = clsTrip.GetTripNotesMaster(filteredWhere, orderByClause, iDisplayLength, iDisplayStart, true);


    List<clsTrip> lstTripNotesGrv = new List<clsTrip>();
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        clsTrip lsttripNotes = new clsTrip();
        lsttripNotes.clrFullName = ds.Tables[0].Rows[i]["clrFullName"].ToString();

        if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i]["trpDate"].ToString()))
            lsttripNotes.trpDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["trpDate"].ToString());
        else
            lsttripNotes.trpDate = DateTime.MinValue;

        lsttripNotes.clrPhone = ds.Tables[0].Rows[i]["clrPhone"].ToString();
        lsttripNotes.clrRelationshipToMember = ds.Tables[0].Rows[i]["clrRelationshipToMember"].ToString();
        lsttripNotes.clrOrganization = ds.Tables[0].Rows[i]["clrOrganization"].ToString();

        if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i]["trpIsGrievance"].ToString()))
            lsttripNotes.trpIsGrievance = Convert.ToBoolean(ds.Tables[0].Rows[i]["trpIsGrievance"].ToString());
        else
            lsttripNotes.trpIsGrievance = false;
        lsttripNotes.trpNote = (ds.Tables[0].Rows[i]["trpNote"].ToString());

        lstTripNotesGrv.Add(lsttripNotes);
    }
    int TotalRec = Convert.ToInt32(ds.Tables[1].Rows[0][0]);

    var result = from c in lstTripNotesGrv
                 select new[] { 
                       //Convert.ToString(c.pronID),                               
                       c.trpDate !=null && c.trpDate!=DateTime.MinValue ? string.Format("{0:MMM d, yyyy}",c.trpDate):"-",
                       c.clrFullName.ToString(),
                       c.clrPhone.ToString(),
                       c.clrRelationshipToMember.ToString(),
                       c.clrOrganization.ToString(),
                       ( Convert.ToBoolean(c.trpIsGrievance)?"Yes":"No"),
                       c.trpNote
                   };

    JavaScriptSerializer jss = new JavaScriptSerializer();
    return jss.Serialize(new
    {
        sEcho,
        iTotalRecords = TotalRec,
        iTotalDisplayRecords = TotalRec,
        aaData = result
    });
}

【讨论】:

  • 很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-26
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多