asp.net-mvc-4 – 如何在MVC 4中每3秒刷新一次局部视图?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-4 – 如何在MVC 4中每3秒刷新一次局部视图?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要根据已完成的作业数量来更新进度条.完成的作业数存储在sql Server DB的作业表中.我需要我的ASP.NET MVC 4应用程序每隔3秒查询数据库以查找竞争数量,并使用此数据更新部分视图中保存的进度条.计时器工作,并在StatusController中调用我的_getforStatus操作,它似乎调用EntityDB,但似乎永远不会在计时器告诉之前调用视图.如何让进度条每3秒刷新一次?

我的_Layout.cshtml视图的标题调用了StatusController中的计时器的启动,如下所示:

  1. <head>
  2. ...
  3. @Html.Action("InitTimer",'Status")
  4. ...
  5. </head>

此外,在_Layout视图中,我将局部视图称为Jumbotron,如下所示:

  1. <div class="jumbotron" id=progress">
  2. @{Html.RenderAction("_GetforStatus","Status");}
  3. </div>

Status控制器的编码如下:

  1. public class StatusController : Controller
  2. {
  3. IntegrationDBEntities _db;
  4.  
  5. Private Timer timer1;
  6.  
  7. Public void initTimer()
  8. {
  9. timer1 = new Timer();
  10. timer1.elapsed += new ElapsedEventhandler(timer_Elapsed(;
  11. timer1.interval = 3000;
  12. timer1.Start();
  13. }
  14.  
  15. Private void timer_Elapsed(Object sender,EventArgs e)
  16. {
  17. _GetforStatus();
  18. }
  19.  
  20. [ChildActiononly]
  21. public PartialViewResult _GetforStatus(0
  22. {
  23. _db = new IntegrationDBEntities();
  24. ViewDataModel - _db.Jobs.ToList();
  25. return partialView();
  26. }

编辑:
我还尝试了以下Ajax代码.我没有错误,但我的进度条从未更新过:

  1. <script>
  2. function loadPartialView() {
  3. $.ajax({
  4. url: '@url.Action("_GetforStatus',"Status")",type: 'GET',dataType: 'html',success: function(result) {
  5. $('progress').html(result);
  6. }
  7. });
  8. }
  9.  
  10. $function () {
  11. loadPartialView();
  12. window.setInterval("loadPartialView()",3000);
  13. });
  14. </script>

我不确定它是否不起作用bc我没有在JS中正确表示“Html.RenderAction”或者是什么.

解决方法

我认为您需要对ajax调用进行一些更改.以下是我如何进行通话的示例
  1. $.ajax({
  2. url: '@Url.Action("Action","Controller")',type: 'post',cache: false,async: true,data: { id: "frmUser" },success: function(result){
  3. $('.divPartial').html(result);
  4. }
  5. });

在你的控制器上我不认为你只需要儿童行动.您还要返回一个空的局部视图对象.它应该是

  1. return partialView('_partialName',Model);

终于在你的jquery中保持呼叫发生你需要重新触发呼叫.尝试这样的事情

  1. $(document).ready(function(){
  2. function RefreshPartial(){
  3. //this will wait 3 seconds and then fire the load partial function
  4. setTimeout(function(){
  5. loadPartialView();
  6. //recall this function so that it will continue to loop
  7. RefreshPartial();
  8. },3000);
  9. }
  10. //initialize the loop
  11. RefreshPartial();
  12. });

猜你在找的asp.Net相关文章