ASP.NET Updating a list using jQuery AJAX

551 views Asked by At

I'm displaying a list on the Default.aspx page that contains objects (persons) fetched from the database:

[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).
}

Method to fill the table:

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

Every 10 seconds this method should be called again without refreshing the page so that the list gets updated:

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

The problem is that I cannot call the fillTable fuction from the static [WebMethod] getPersonList(). How can I make this work?

1

There are 1 answers

0
Sam On

I finaly found a good solution. Because it looks like it's not possible to run the fillTable() method (non static) inside the static [WebMethod] getPersonList() method I couldn't refresh the content using the Code-Behind where I needed access to UI Elements in a static method. What I did is convert to persons-list into a JSON-object and sent it to my jQuery success function (where the needed UI elements are targetable):

// 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
    });
}