標籤:
HttpContext基於HttpApplication的處理管道,由於HttpContext對象貫穿整個處理過程,所以,可以從HttpApplication處理管道的前端將狀態資料傳遞到管道的後端,完成狀態的傳遞任務做個小demo
1.控制器:
public class TestController : Controller { string key = "data"; public ActionResult Index() { return View(); } /// <summary> /// 定時器擷取快取資料 /// </summary> /// <returns></returns> [HttpPost] public JsonResult GetData() { string data = Convert.ToString(HttpContext.Cache.Get(this.key)); if (!string.IsNullOrEmpty(data)) { return this.Json(new { success = true, data = data }); } else { return this.Json(new { success = false, time = DateTime.Now.ToString("ss"), data = data }); } } /// <summary> /// 開啟輸入緩衝值介面 /// </summary> /// <returns></returns> [HttpGet] public ActionResult CreateCacheData() { return View(); } /// <summary> /// 將資料插入緩衝 /// </summary> /// <param name="value"></param> /// <returns></returns> [HttpPost] public void InsertCache(string value) { HttpContext.Cache.Insert(this.key, value); } }
2.視圖
Index.cshtml:
@{ ViewBag.Title = "Index"; Layout = null;}<script src="~/Scripts/jquery-1.8.2.min.js"></script><script src="~/Scripts/jquery.timers-1.2.js"></script><button id="btnStart">開始定時器</button><script> $(function () { //定時器開始 $("#btnStart").bind("click", function () { $("body").everyTime("3s", "timer", function () { $.ajax( { type: ‘post‘, url: ‘/Test/GetData‘, success: function (r) { if (r.success) { console.log("擷取到資料,json字串為" + JSON.stringify(r.data)); } else { console.log("(" +r.time + ")秒沒有擷取到資料"); } } }); }) }); })</script>
jquery.timers-1.2.js 是定時器jquery外掛程式
定時器外掛程式下載
CreateCacheData.cshtml:
@{ ViewBag.Title = "CreateCacheData";}<script src="~/Scripts/jquery-1.8.2.min.js"></script><input id="txtData"/><button id="btnSave" > 插入伺服器緩衝</button><script> $(function () { $("#btnSave").click(function () { var getDataValue = $("#txtData").val(); $.post("/Test/InsertCache", {value:getDataValue}, function () { alert("緩衝插入成功"); }); }) });</script>
3.效果
,
HttpContext.Cache屬性