GotKnowHow.com

How to UrlEncode Plus Sign "+" in QueryString and UrlDecode Plus Symbol in ASP.NET

by


Here's how you can UrlEncode the plus sign (+) in a URL querystring in ASP.NET and then retrieve the plus symbol after UrlDecoding the string.

In this example, I will do a postback and redirect the Server.UrlEncoded string to another page.  First we will replace the "+" sign with "%252b" and then Server.UrlEncode the text:

protected void PostButton_Click(object sender, EventArgs e)
{
        // replace plus sign "+" with "%252b"
        string myTitle = TitleTextBox.Text.Trim().Replace("+", "%252b"); 
        Response.Redirect("~/default.aspx?title=" + Server.UrlEncode(myTitle));
}

Now on the page we redirected to, we will Server.UrlDecode the QueryString and replace "%2b" with the "+" plus symbol:

protected void Page_Load(object sender, EventArgs e)
{
       if (!Page.IsPostBack)
        {

            // Get Querystring for Title, if it exists
            string pageTitle = Server.UrlDecode(Request.QueryString["title"]);
           
            if (!string.IsNullOrEmpty(pageTitle))
            {
  // replace encoded plus sign "%2b" with real plus sign +
  pageTitle = Regex.Replace(pageTitle, "%2b", "+", RegexOptions.IgnoreCase);
  PageTitleTextBox.Text = pageTitle;         
            }
        }
}

So that's a simple technique that you can use to Server.UrlEncode a string that contains the Plus sign and then retrieve the plus symbol after the querystring has been decoded using Server.UrlDecode in ASP.NET and C#.

 


0
1

1 Comment

anonymous by webmonkey on 2/13/2012
i did not want the plus sign in the subject of an email. so

ename = Server.UrlEncode(ename).Trim().Replace("+", "%20")

Add your comment

by Anonymous - Already have an account? Login now!
Your Name:  

Comment:  
Enter the text you see in the image below
What do you see?
Can't read the image? View a new one.
Your comment will appear after being approved.


Did this article help you out, share it with your friends:

Ask a Question

140 characters left

Recent Articles