本文描述如何重新加載整個PartialView。
Controller:
public class HomeController : Controller { public static int i = 0; /// <summary> ///這個數組是超過來的,懶的改了。 /// </summary> public static string[] quotes = { "The first 90% of the code accounts for the first 90% of the development time.","The remaining 10% of the code accounts for the other 90% of the development time", "In order to understand recursion, one must first understand recursion", "I have always wished for my computer to be as easy to use as my telephone;", "my wish has come true because I can no longer figure out how to use my telephone.", "The gap between theory and practice is not as wide in theory as it is in practice.", "Nine people can’t make a baby in a month" }; public ActionResult Index() { return View(); } [OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 1)] public ActionResult Quote() { //注釋這個地方,原本是隨機生成數組的index,結果上來我就悲劇, 連續幾次都是用一個數,想了想為了效果明顯還是改成其他的吧。 //var r = new Random(); //var rv = r.Next(0, 4); if (i == 6) { i = 0; } ViewBag.Quote = quotes[++i]; return PartialView("_Quote"); } }
Index頁面:
@{ ViewBag.Title = "Home Page"; } <script type="text/javascript"> function BtnClick() { //注意這一行,是針對的,后台Action中沒有設置頁面緩存機制的情況的。隨機產生一個數就是,為了讓頁面加載的時候不在緩存中讀。 //$('#quote').load('/home/quote/' + Math.random()); $('#quote').load('/home/quote/'); } </script> <p> <input type="button" onclick="BtnClick()" value="刷新局部頁" /> <div id="quote"> </div> </p>
_Quote.cshtml:
<h3>@ViewBag.Quote</h3>
主要的思路是:
1.在主頁面上定義個一div。
2.點擊按鈕(或者其他動作),觸發div的load事件。
3.在前端js或者后台Action中避免頁面緩存。
4.頁面加載。