2011-04-14 53 views
1

我正在做一個ASP.Net頁面的高級規範,該頁面可能會顯示一些延遲的數據。在不刷新的情況下將新數據加載到頁面上

頁面加載時,呈現的初始數據將來自本地數據庫(這將在呈現中快速呈現)。我想要的是一個單獨的過程,用於尋找更新的數據(來自我擁有的任何其他服務)。這比較費時,但想法是呈現數據,然後如果找到更新的數據,則將其附加到現有頁面的頂部。

我想就如何做到這一點的一些建議。

技術範圍是ASP.Net 4.0,C#MVC3和HTML5。

謝謝。

+2

您正在尋找的術語是AJAX。 – 2011-04-14 16:41:54

回答

2

AJAX with jQuery是實現此目的的好方法。因此,例如,你可以把你的標記內容佔位符DIV:

<div id="result" data-remote-url="@Url.Action("Load", "SomeController")"></div> 

,然後一旦DOM加載:

$(function() { 
    $.ajax({ 
     url: $('#result').data('remote-url'), 
     type: 'POST', 
     beforeSend: function() { 
      // TODO: you could show an AJAX loading spinner 
      // to indicate to the user that there is an ongoing 
      // operation so that he doesn't run out of patience 
     }, 
     complete: function() { 
      // this will be executed no matter whether the AJAX request 
      // succeeds or fails => you could hide the spinner here 
     }, 
     success: function(result) { 
      // In case of success update the corresponding div with 
      // the results returned by the controller action 
      $('#result').html(result); 
     }, 
     error: function() { 
      // something went wrong => inform the user 
      // in the gentler possible manner and remember 
      // that he spent some of his precious time waiting 
      // for those results 
     } 
    }); 
}); 

,其中負載控制器動作將與遠程服務進行通信,並返回一個包含數據的局部視圖:

public ActionResult Load() 
{ 
    var model = ... go ahead and fetch the model from the remote service 
    return PartialView(model); 
} 

現在,如果這個獲取數據的爲I/O密集型你可以採取廣告有效的asynchronous controllers I/O完成端口,這將避免您在從遠程源獲取數據的冗長操作中危害工作線程。

相關問題