views:

92

answers:

1

I am in the design stage at the moment and was wondering how I would update a table every 5 seconds.

My table will display read-only data returned from my model.

Normally my view would just have <table></table> HTML and then a foreach loop to write out the data.

However because I want to refresh this whole table every 5 seconds I am unsure how to implement it.

I know there is the javascript setinterval function but I'm also unsure what to do at that point. Would it be something like this?

eg/

function getdata()
{
    $.getJSON("/mycontroller/mymethod"), 

                 function(data) {

                $.each(data, function(i, item) {
                    var row = {  item.ID, item.Date,
                         item.Title
                    };
               $(#table).tableInsertRows(row);
                });

            });
}
    setInterval( "getdata", 5000 );
A: 

It might be easiest to have your mymethod action render a view instead of returning JSON. Then you could just set the innerHTML of a div to the ajax response.

Otherwise your approach will work, but you obviously have to delete the existing table rows first:

$('#table').tableRemoveRows({from:0, length:???});

Edit

re-reading your question, it sounds like you're asking more about setInterval than actually creating the table. You need to keep re-registering the callback, so something like this:

function getdata()
{
    $.getJSON("/mycontroller/mymethod"), function(data) {

        $.each(data, function(i, item) {
                var row = {  item.ID, item.Date,
                     item.Title
                };
           $(#table).tableInsertRows(row);
        });

        setInterval( getdata, 5000 );

    });
}
setInterval( getdata, 5000 );
Gabe Moothart
When you return a Partial View does only the raw HTML get seen on the AJAX success enabling you to just set the innerHTML?
Jon
I'm asking about both really. I think I get the setInterval but just not sure the best way to get the new data and drawn out to the browser
Jon
@Jon On the server you `return View()` from your `mymethod` action. On the client you'd use `$.get` instead of `$.getJSON` and then just grab the responseText.
Gabe Moothart
Depending on the volume of data, you may want to consider looking at javascript templating so you can return JSON instead of markup. (MS has a beta version out that I like.)
Ryan