开发者

Asp.net mvc3 periodic refresh of results without reloading the page

I'm using asp.net MVC3 for a website that displays in a view a query result (managed in the controller) using a foreach.

What I want to do now is to automatically refresh the output of the query every tot time, without refreshing the page.

How can I do that using ajax?

This is the code of the View:

@{
    string firstTime = "";
}
 @foreach( var database in Model)
 {

        if (!(firstTime == database.DB))
        {
          <h3> @database.DB </h3>
        }
开发者_开发知识库
           <div class="logContainer" onclick="location.href='/logs/Details?databaseID=@database.DB&exceptionName=@database.Exception&exceptionsOccurred=@database.Count';">
                <div class="counter"><b>@database.Count</b></div> 
                <div class="exceptionName"> Exceptions of Type: @database.Exception</div>
                <div class="date">Siste: @database.LastOccurred</div>
           </div>
       <hr />

     firstTime = database.DB; 
}


You could use the window.setInterval javascript method to send AJAX requests to the server at regular intervals and refresh the corresponding part of the DOM. For example if you wanted to refresh the contents every 10 seconds:

window.setInterval(function() {
    $.post('@Url.Action("someaction", "somecontroller")', function(result) {
        $('#results').html(result);
    });
}, 10 * 1000);

This will send an AJAX request to the controller action which in turn could return a partial view containing the updated results:

pubilc ActionResult SomeAction()
{
    SomeViewModel model = ...
    return PartialView(model);
}

The result of this partial view will then be injected into some DOM element with id="results".


You could either pass the query result using JSON and render the HTML yourself from javascript, or separate the for-each code to a different partial view, and using jQuery's $.ajax method change the query result's div html with the new response


Why not put your data in to an existing grid control such as DataTables, which is lightweight pretty fast and extensible. Then, using a javascript timer, tell the data table to refresh it's contents.

I've used this with MVC3 with great effect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜