当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > asp.net中url地址传送中文参数时的两种解决方案

ASP.NET
ASP.NET在上传文件时对文件类型的高级判断的代码
JQuery运用ajax注册用户实例(后台asp.net)
Asp.net与SQLserver一起打包部署安装图文教程
asp.net 上传下载输出二进制流实现代码
asp.net(C#)解析Json的类代码
asp.net 截取字符串代码
asp.net ubb使用代码
asp.net XML文件操作实现代码
asp.net利用HttpModule实现防sql注入
ASP.NET(C#)中操作SQLite数据库实例
asp.net(c#)ref,out ,params的区别
asp.net(C#)防sql注入组件的实现代码
asp.net FCKeditor自定义非空验证
Asp.net TreeView来构建用户选择输入的方法 推荐
asp.net(C#)函数对象参数传递的问题
Asp.net中的GridView导出遇到的两个问题和解决方法
asp.Net 中获取一周第一天,一月第一天等实现代码
asp.net MaxLengthValidator 最大长度验证控件代码
C# 通用文件上传类
asp.net 自定义控件实现无刷新上传图片,立即显示缩略图,保存图片缩略图

ASP.NET 中的 asp.net中url地址传送中文参数时的两种解决方案


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 44 ::
收藏到网摘: n/a

前天遇到一个地址传递中文参数变为乱码的问题,同样的两个web Project,一个是vs2003,一个是vs2005,前者可以,后者就是不可以。 在Web.comfig中配置 是一样的:
<globalization requestEncoding="gb2312" responseEncoding="gb2312"/>
页面Header部分也都有
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
真是奇怪,
只好用了笨办法:
写参数:
复制代码 代码如下:

string strurl = PreUrl + "?word={0}&sort={1}&check={2}";
strurl = string.Format(strurl, HttpUtility.UrlEncode(this.txtSearchTxt.Text.Trim(), System.Text.Encoding.GetEncoding("GB2312")), this.radioSortDesc.SelectedIndex.ToString(), CheckState.ToString());
Page.Response.Redirect(strurl);
//注意编码方式为gb2312

读参数:
复制代码 代码如下:

try
{ if (Page.Request.QueryString["word"] != null)
{ _word = Convert.ToString(HttpUtility.UrlDecode(Page.Request.QueryString["word"], System.Text.Encoding.GetEncoding("GB2312"))); }
}
catch { _word = String.Empty; }
///注意编码方式为gb2312,与前面对应

后来,看了孟子的文章,才发现有更好的解决方案:
用Javascript!
写一个方法放在基类页面中
复制代码 代码如下:

public void PageLocation(string chineseURL)
{
if(chineseURL==null || chineseURL.Trim().Length==0 )
{return;//还可能不是一个合法的URL Tony 2007/11/15
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "AgronetPageLocationTo", "<script type='text/javascript' language='javascript'> window.location.href='"+chineseURL+"';</script>");
}

然后在页面中调用
复制代码 代码如下:

string strurl = PreUrl + "?word={0}&sort={1}&check={2}";
strurl = string.Format(strurl, this.txtSearchTxt.Text.Trim(), this.radioSortDesc.SelectedIndex.ToString(), CheckState.ToString());
PageLocation(strurl);

注意后种方法用了Javasrcipt,实际应用在分页时需要保持中文参数,最好还是用window.Location.Href方法!
最后,如果一要在javascript与.net后台代码进行对话,可以这样:
复制代码 代码如下:

<script language= "JavaScript " >
function GoUrl()
{
var Name = "中文参数 ";
location.href = "B.aspx?Name= "+escape(Name);
}
</script >
<body onclick= "GoUrl() " >

接收:
复制代码 代码如下:

string Name = Request.QueryString[ "Name "];
Response.Write(HttpUtility.UrlDecode(Name));

要点是:
将传递的中文参数进行编码,在接收时再进行解码。
完。