Search code examples
javascripturlampersandhtml-escape-characters

Passing an & through a javascript generated URL?


I have this line of code that is executed when a ddl in my page is changed -

location.href = '@Url.Action("Edit", "Page", new { UserId = (string)null })/' + '@ViewBag.userId' + '?status=' + '@ViewBag.status' + '&pageNo=@ViewBag.PageNo';

The link was working fine with just an &, but after checking the markup validator, http://validator.w3.org/check, it suggested I replace & with & and I have done so in the above line of code. Now though, when I change the ddl & literally appears in the url and the page does not work properly (as filtered by the ddl).

<script type="text/javascript">
$(document).ready(function () {
 $(".ddl").change(function () { changePage(); });

 }); 

    function changePage() {
        location.href = '@Url.Action("Edit", "Page", new { UserId = (string)null })/' + '@ViewBag.userId' + '?status=' + '@ViewBag.status' + '&amp;pageNo=@ViewBag.PageNo';
}

</script>

Could someone tell me what I'm doing wrong?


Solution

  • The basic problem is that you are using XHTML by serving it as text/html

    If the document was being parsed as XML then you would need to represent & as &amp; inside a script element, but since you are claiming the document is HTML, then you can't do that.

    See the compatibility guidelines either

    • keep your JS in an external file
    • wrap it with CDATA markers
    • use HTML instead of XHTML