简体   繁体   中英

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" .

您可以使用JSON传递查询结果并自己从javascript呈现HTML,也可以将for-each代码分离到不同的局部视图,然后使用jQuery的$ .ajax方法以新响应更改查询结果的div html。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM