2015-06-17 62 views
-1

我顯示包含的對象(人)Default.aspx頁面上的列表從數據庫中獲取的列表:ASP.NET更新使用jQuery AJAX

[WebMethod] 
[ScriptMethod(UseHttpGet = false)] 
public static void getPersonList() 
{ 
    DatabankService dbs = new DatabankService(); 
    persons = dbs.getPersons()); 
    // fillTable(persons) is not possible here (not possible in static method). 
    // fillTable code also cannot be place here because it uses UI Elements from default.aspx to create the table (same problem as above). 
} 

方法來填充表:

public void fillTable(List<Person> persons) 
{ 
    // make colums and rows and will with data (foreach person in..) 
} 

每10秒鐘此方法應再次調用,而不使列表被更新刷新頁面:

$(function() { 
    setInterval(function() { 
     getData(); 
    }, 10000); 
}); 

function getData() { 
    $.ajax({ 
     type: "POST", 
     async: true, 
     url: "Default.aspx/getPersonList", 
     dataType: "json", 
     contentType: "application/json; charset=utf-8", 
     error: function (jqXHR, textStatus, errorThrown) { 
      // error 
     }, 
     success: function (data) { 
      // success 
     } 
    }); 
} 

問題是我無法從靜態[WebMethod] getPersonList()調用fillTable函數。我該如何做這項工作?

+0

你說的意思是「無法調用fillTable功能」 ?它不工作,它失敗了?代碼聽起來不錯,所以有可能是你忘記的小事。 –

+0

在靜態方法內部調用一個方法給出了一個錯誤,我想這是不可能的:「非靜態字段,方法或屬性... Filltable()」需要對象引用。 – Sam

+0

在Persons類中創建一個名爲fillTable()的方法,然後從getPersonList()方法返回該方法。另外getPersonList()應該返回一串json數據。 –

回答

0

我最終找到了一個很好的解決方案。由於看起來無法在靜態[WebMethod] getPersonList()方法內運行fillTable()方法(非靜態),我無法使用代碼隱藏來刷新內容,而我需要以靜態方式訪問UI元素方法。我所做的是轉換到人名單成JSON對象,並把它交給我的jQuery的成功,函數(其中所需要的UI元素靶向):

// getPersonList() 
... 
string result = JsonConvert.SerializeObject(persons); 
return result; 

// jQuery success 

success: function (data) { 
    response = JSON.parse(data.d); 

    $.each(response, function (i, item) { 
     // fill table using jQuery 
    }); 
}