且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-25 18:29:20

在cshtml或aspx/ascx中制作链接时,若参数可能是中文,则需要使用HttpUtility.UrlEncode():


  1.  
  2. [html] view plaincopy  
  3. 01.@Html.Link("角色", "/SFC/Users/Users2Roles?user=" + HttpUtility.UrlEncode(User.Identity.Name))    

而在对应的Action中,一切照常,不需要"Decode”(也有帖子说需要,但本人实验的结果是不需要):


  1.  
  2. html] view plaincopy  
  3. 01.public ActionResult Users2Roles(string user)    
  4. 02.{    
  5. 03.    ViewBag.User = user;    
  6. 04.    return View(SFCRoles.GetAllRoles());    
  7. 05.}    
  8. 06.[HttpPost]    
  9. 07.public ActionResult Users2Roles(string user, FormCollection collection)    
  10. 08.{    
  11. 09.    ViewBag.User = user;    
  12. 10.    
  13. 11.    try    
  14. 12.    {    
  15. 13.    }    
  16. 14.}    
此外还能解决类似空格和特殊字符的问题,比如当你想让一个页面关闭后回到另外一个页面,而另外一个页面的链接中偏偏有两个以上参加就,因此里边有个“&”,就可以:使用:

 


  1.  
  2. [html] view plaincopy  
  3. 01.@Html.Link("x", "/SFC/Categories/Delete?rootID=" + root.ID + "&id=" + Model.ID, showInNewWindow:false, returnUrl: HttpUtility.UrlEncode(Request.Url.ToString()))    

这个Html.Link是我自己编写的Helper,如果直接用a,也一样可以。

但是这么写来写去毕竟太长了太麻烦了,所以如果经常使用returnUrl请参考我另外一个帖子:http://cheny.blog.51cto.com/3988930/1100102 在最后几行2011-08-18的补充。两个问题居然碰到一起了。
 

可参考:

http://***.com/questions/3101823/extract-chinese-text-from-query-string

http://***.com/questions/1380617/request-url-parameter

http://***.com/search?q=Chinese+Parameter+URL+asp.net (***上面所有类似的问题)



本文转自火星人陈勇 51CTO博客,原文链接:http://blog.51cto.com/cheny/1100221