天天看點

asp.net怎樣在URL中使用中文、空格、特殊字元

在cshtml或aspx/ascx中制作連結時,若參數可能是中文,則需要使用HttpUtility.UrlEncode():

[html] view plaincopy  

[email protected]("角色", "/SFC/Users/Users2Roles?user=" + HttpUtility.UrlEncode(User.Identity.Name))    

而在對應的Action中,一切照常,不需要"Decode”(也有文章說需要,但本人實驗的結果是不需要):

html] view plaincopy  

01.public ActionResult Users2Roles(string user)    

02.{    

03.    ViewBag.User = user;    

04.    return View(SFCRoles.GetAllRoles());    

05.}    

06.[HttpPost]    

07.public ActionResult Users2Roles(string user, FormCollection collection)    

08.{    

09.    ViewBag.User = user;    

10.    

11.    try    

12.    {    

13.    }    

14.}    

此外還能解決類似空格和特殊字元的問題,比如當你想讓一個頁面關閉後回到另外一個頁面,而另外一個頁面的連結中偏偏有兩個以上參加就,是以裡邊有個“&”,就可以:使用:

[email protected]("x", "/SFC/Categories/Delete?rootID=" + root.ID + "&id=" + Model.ID, showInNewWindow:false, returnUrl: HttpUtility.UrlEncode(Request.Url.ToString()))    

這個Html.Link是我自己編寫的Helper,如果直接用a,也一樣可以。

可參考:

<a href="http://stackoverflow.com/questions/3101823/extract-chinese-text-from-query-string">http://stackoverflow.com/questions/3101823/extract-chinese-text-from-query-string</a>

<a href="http://stackoverflow.com/questions/1380617/request-url-parameter">http://stackoverflow.com/questions/1380617/request-url-parameter</a>

本文轉自火星人陳勇 51CTO部落格,原文連結:http://blog.51cto.com/cheny/1100221

繼續閱讀