一般的前台和后台交互传值很简单,我习惯了用Ajax,但是最近遇到一个问题,前端调用后台一个方法后,需要刷新整个页面,但是这时候前台和后台方法都没有走完,之前利用JQuery获取的那些值都清空了,于是就想到了Cookie,因为Cookie可以保存在浏览器中,我们可以设置它的有效时间。以下是小编的代码。
前台方法
function queryListByMonth() {
var queryMonth = $('#QueryTime').val();
$('#viewChapterID').val(queryMonth);
window.location.href = '../EmployeeServices/PunchList?queryMonth=' + queryMonth.trim();
};
后台写入cookie
public ActionResult PunchList()
{
var strMonth = Request["queryMonth"];
if (strMonth != null)
{
var cookiesMonth = new HttpCookie("queryMonth");
cookiesMonth["monthValue"] = strMonth;
cookiesMonth.Expires = DateTime.Now.AddSeconds(1);
Response.Cookies.Add(cookiesMonth);
}
var model = new EmployeeServicePunchList();
model.PunchList = QueryPurchList();
return View(model);
}
后台读取cookie
HttpCookie cookie = Request.Cookies["queryMonth"];
if (cookie != null)
{
var month = cookie["monthValue"];
TimeSpan ts = new TimeSpan(0, 0, 0, 0);//时间跨度
Response.Cookies.Remove("cookie");//清除
startTime = DateTime.Parse(month);
endTime = LastDayOfMonth(startTime);
}
如果在自己在编写的过程中,不想让别人在浏览器中查看cookie的值,我们可以给cookie加密,取值的时候再解密。代码如下
cookiesMonth["monthValue"] = HttpUtility.UrlEncode(queryMonth, Encoding.GetEncoding("UTF-8"));//加密
HttpCookie demo= Request.Cookies["(queryMonth"]
HttpUtility.UrlDecode(demo["monthValue"]);//解密
cookie传值,耗费性能,大家慎用,但是在某些场合还是可以考虑的,其实cookie还有很多用途,期待大家的解密。