利用cookie传值

   一般的前台和后台交互传值很简单,我习惯了用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还有很多用途,期待大家的解密。

评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值