2015-06-17 58 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 
    }); 
}