天天看点

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

继续阅读