0

I'm sending a parameter to my Controller via json which contains and ampersand and the string gets cut off after that character. Been searching for hours and cannot find a solution.

JavaScript

var url = '/Common/DownloadFile?fileName=Me&You.xlsx';
$.ajax({
    type: 'POST',
    url: url,
    data: {},
    success: function (data) {}
});

Controller

public ActionResult DownloadFile(string fileName)
{
    // Here the param is coming in as 'Me'
    // Code removed for clarity
}
tqrecords
  • 542
  • 1
  • 5
  • 20

2 Answers2

2

The ampersand is used to separate arguments in a URL. If you want the ampersand to be part of a parameter value, you need to URLencode it using a method like encodeURIComponent().

In this particular case, the encoded version of Me&You.xslx would be Me%26You.xlsx. If you specify that in your GET request your application should get the expected value.

Peter
  • 2,526
  • 1
  • 23
  • 32
2

In urls & needs to be escaped because it is used to add new params like

http://hello.com"?fileName=Something&otherFileName=SomethingElse

You need to escape the ampersand by percent encoding it like this:

/Common/DownloadFile?fileName=Me%26You.xlsx

Here is more information on url parameter escaping escaping ampersand in url

  • Perfect, issue was I was using encodeURIComponent() around the entire url but it worked after doing `code`var url = fileUrl + '?fileName=' + encodeURIComponent('Me&You.xlsx')`code` – tqrecords Sep 12 '17 at 16:56