2014-02-10 53 views
1

在ASP.net中使用JQuery DataTables並試圖從C#返回JSON數據給它#WebMethod使用JSON在ASP.net中的DataTables

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%" } 
    ] 
}); 
+0

網址是否正確?在一個例子中,你有'page.aspx/Data',而在其他情況下則是'../ page.aspx/Data' ... – MikeSmithDev

+0

yah其正確。我也嘗試過使用「page.aspx/Data」 – Jag

+0

我看到您正在爲您的數據發送一個空對象? lisata:{}'我會在那裏發佈我的數據 – photowalker

回答

2
$("#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(); 
                } 
        }); 
       } 
      }); 

這是爲我工作

檢查它out

+0

感謝,現在它擊中斷點和獲取數據,仍然在jquery.dataTables.js在\t \t \t var aData = _fnGetObjectDataFn(oSettings.sAjaxDataProp)(json);\t \t \t for(var i = 0,iLen = aData.length; i Jag

+0

您可以還請分享您的C#web方法。謝謝。 – Jag

+0

我已經在新的答案中添加了網絡方法檢查出 –

0

結帳this page。看看「發送給服務器的參數」。我認爲dataTables期望您的服務器端webmethod接受這些值。您可以通過使用fnServerData(在同一頁面上)選項覆蓋它發送的內容。這是在數據發送到後端之前調用的,因此您可以控制發送的內容。

這個post也許有用。

+0

謝謝。有一些關於fnServerData的信息。 – Jag

0

你好大哥這個屬性添加到您的數據表

---- 「bServerSide」:真實, 這樣

$(".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%" } 
    ] 
}); 
+0

已結束,但無法使用。仍然沒有達到方法的突破點。謝謝,雖然 – Jag

+0

在代碼後面用[WebMethod()] 替換[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)] –

0
[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 
    }); 
} 
+0

謝謝..最後工作。 – Jag

+0

我很樂意幫助你 –