程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net中url地址傳送中文參數時的兩種解決方案

asp.net中url地址傳送中文參數時的兩種解決方案

編輯:ASP.NET基礎
在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));

要點是:
將傳遞的中文參數進行編碼,在接收時再進行解碼。
完。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved