最近在学.net和.net ajax,发现在button提交后ajax无法保存视图状态,想了一下,可以用url、cookies或隐藏的textbox来传递
url和textbox方法比较简单就没有多想,主要是测试了cookies的方法,发现只要有中文会就乱码
在网上找了一圈发现解决方法都不理想,主要问题出在于,C#中用UrlEncode来编码或javascript中用的却是unescape来解,反之也是这个道理,总是不行
也试过网上的Javascript自定义函数UrlEncode、UrlDecode,也是不起作用。
后来去看了一下Javascript的函数表,发现原来Javascript中有decodeURI和encodeURI两个函数,可以实现与.net程序之间cookies的完美传递。
真是郁闷的一B啊
.net端
private void setCookie(string name,string value)
{
System.Web.HttpCookie cookie = new HttpCookie(name, System.Web.HttpUtility.UrlEncode(value));
cookie.Expires = System.DateTime.Now.AddDays(30);
cookie.Path = "/";
System.Web.HttpContext.Current.Response.AppendCookie(cookie);
}
private string getCookie(string name)
{
if (Request.Cookies[name] != null)
{
return System.Web.HttpUtility.UrlDecode(Request.Cookies[name].Value);
}
else
{
return "";
}
}
{
System.Web.HttpCookie cookie = new HttpCookie(name, System.Web.HttpUtility.UrlEncode(value));
cookie.Expires = System.DateTime.Now.AddDays(30);
cookie.Path = "/";
System.Web.HttpContext.Current.Response.AppendCookie(cookie);
}
private string getCookie(string name)
{
if (Request.Cookies[name] != null)
{
return System.Web.HttpUtility.UrlDecode(Request.Cookies[name].Value);
}
else
{
return "";
}
}
Javascript端
function setCookie(name,value)
{
var Days = 30;
var expTime = new Date();
expTime.setTime(expTime.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ encodeURI(value) + ";expires=" + expTime.toGMTString()+";path=/";
}
function getCookie(name)
{
var arrCookies = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arrCookies != null) return decodeURI(arrCookies[2]); return null;
}
{
var Days = 30;
var expTime = new Date();
expTime.setTime(expTime.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ encodeURI(value) + ";expires=" + expTime.toGMTString()+";path=/";
}
function getCookie(name)
{
var arrCookies = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arrCookies != null) return decodeURI(arrCookies[2]); return null;
}