0

I had an asp.net-mvc site and I have an issue where I had an "&" in my query string that I am building with javascript and then using ajax to my server. Something like this:

 www.mysite.com/MyController/Load?Tag=M&Ms

when I passed this to my server using ajax, it was showing up as

Tag="M"

so, in my javascript code, I changed my code from this:

  "Load?Tag=" + tag;

to:

  "Load?Tag=" + encodeURIComponent(tag);

and this fixed my issue. My server code looks like this

 public ActionResult Load(ProjectParams projectParams)
 {
      //go do stuff
 }

where ProjectParams looks like this:

public class ProjectParams
{
    public string Tag {get;set;}
}

So everything was great until I realized that making this change on the javascript side, had a knockon effect. I just ran into an issue where if I have spaces in my tag name, it shows up on the server as:

  My%20Tag%20Name

instead of:

  My Tag Name

what is the correct way to encode on the javascript side for a url querystring and ensure that it shows up properly on the serverside controller action

leora
  • 188,729
  • 360
  • 878
  • 1,366
  • did you see this http://stackoverflow.com/questions/1211229/in-a-url-should-spaces-be-encoded-using-20-or – kanchirk Jun 03 '15 at 20:43
  • possible duplicate: http://stackoverflow.com/questions/22012472/mvc-asp-net-querystring-incorrect – McArthey Jun 03 '15 at 20:44
  • @McArthey - this question says "Use encodeURIComponent" on the javascript side which i specified in my question that i am already doing – leora Jun 03 '15 at 20:45
  • @leora Maybe you should attribute Tag property with [AllowHtml] – kanchirk Jun 03 '15 at 20:47
  • @kanchirk - this seems like a very odd way to solve this issue. Can you elaborate? – leora Jun 03 '15 at 20:49
  • @leora: I would expect that MVC would automatically decode the Query String parameter in that scenario; it's peculiar that it isn't. I assume you've confirmed that it isn't getting double-encoded somehow? I.e., that your Query String reads, literally, `Tag=My%20Tag%20Name` and not `Tag=My%2520Tag%2520Name`? Worst case you could work around this using .NET's `UrlDecode()` method (e.g., from `WebUtility` or `HttpUtility`), but that's obviously not ideal. – Jeremy Caney Jun 03 '15 at 20:58

1 Answers1

0

you can decode it easily with

Server.UrlDecode()

and you could do that on the setter

Dan Kuida
  • 1,017
  • 10
  • 18