简体   繁体   English

ASP.NET MVC3定期刷新结果,而无需重新加载页面

[英]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. 我将asp.net MVC3用于网站,该网站在视图中使用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? 如何使用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. 您可以使用window.setInterval javascript方法将AJAX请求定期发送到服务器,并刷新DOM的相应部分。 For example if you wanted to refresh the contents every 10 seconds: 例如,如果您想每10秒刷新一次内容:

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: 这将向控制器操作发送一个AJAX请求,该操作又可以返回包含更新结果的局部视图:

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" . 然后,该部分视图的结果将注入到具有id="results" DOM元素中。

您可以使用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. 为什么不将数据放入现有的网格控件(如DataTables)中 ,该控件是轻量级的,非常快速且可扩展。 Then, using a javascript timer, tell the data table to refresh it's contents. 然后,使用JavaScript计时器,告诉数据表刷新其内容。

I've used this with MVC3 with great effect. 我已经将此与MVC3一起使用,效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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