2011-07-28 152 views
6

我需要定期刷新.Net的局部視圖。它與Ajax.ActionLink一起工作,是否有類似的定期刷新功能?我可以做到這一點,而不使用jQuery?定期刷新局部視圖(ASP.Net MVC)

+0

檢查這個http://stackoverflow.com/questions/3167116/asp-net-mvc-refresh-table-data-every-5-seconds – raym0nd

+0

你可以把這個在你的HTML的: raym0nd

+0

有沒有可能沒有js? –

回答

9

禪,你可以通過這樣的代碼做到這一點:

function loadPartialView() { 
    $.ajax({ 
    url: "@Url.Action("ActionName", "ControllerName")", 
    type: 'GET', // <-- make a async request by GET 
    dataType: 'html', // <-- to expect an html response 
    success: function(result) { 
       $('#YourDiv').html(result); 
      } 
    }); 
} 

$(function() { 

    loadPartialView(); // first time 

    // re-call the function each 5 seconds 
    window.setInterval("loadPartialView()", 5000); 

}); 

記住你的行動應該返回PartialView。 我希望它能幫助你!

+0

我一直在尋找非jQuery,但無論如何,謝謝(+1)。 –

+0

這在Chrome和Firefox中適用於我,但不適用於IE 9(沒有打擾其他IE瀏覽器),但現在已經足夠了。 +1 – Yetti

2

也許this可以幫助你。你正在使用哪個版本的MVC?您可以爲輔助方法設置指定的時間間隔。這是我看到不使用js的唯一方式。

+0

我正在使用MVC 2,VS 2010 –

+0

然後,您可能無法使用此方法。但這是我見過不使用js執行此操作的唯一方式,其他所有與js相關的操作都是如此。 –

+1

其實,它使用js,但js只是嵌入式。 –

0

試試這個。

$(document).ready(function() { 
      var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))"; 
      $("#PartialViewDivId").load(url); 
     setInterval(function() { 
      var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))"; 
      $("#PartialViewDivId").load(url); 
     }, 30000); //Refreshes every 30 seconds 

     $.ajaxSetup({ cache: false }); //Turn off caching 
    }); 

它進行初始調用來加載div,然後後續調用在30秒間隔。

在控制器部分中,您可以更新對象並將對象傳遞給局部視圖。

public class ControllerName: Controller 
{ 
    public ActionResult ActionName() 
    { 
     . 
     . // code for update object 
     . 
     return PartialView("PartialViewName", updatedObject); 
    } 
}