dan dan - 2 months ago 16
Javascript Question

Sending url with parameter to action function via javascript

I am trying to open new window using window.open(actionUrl)
the actionUrl is compose form the action address and url as parameter.
so eventually the actionUrl is :
"/Default/Details?url=http://www.someaddress.com?a1=1&a2=2&a3=3"
However in the action the url i get is :
"http://www.someaddress.com?a1=1"
I do not get "&a2=2&a3=3" parameters

Here is the relevant view code:

<div>
<input type="button" value="test" id="btnTest" />
</div>

<script>
var vurl = '@Url.Action("Details", "Default")';
$(function () {
$("#btnTest").click(function () {
var url = "http://www.someaddress.com?a1=1&a2=2&a3=3";
vurl = vurl + url;
window.open(vurl);

});
})

</script>


and this is the controller and action

public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}

// GET: Default/Details/5
public ActionResult Details(string url)
{
return View();
}
}

Answer

You need to use the encodeURIComponent function on the url parameter's value:

var actionUrl = '/Default/Details?url=' + encodeURIComponent('http://www.someaddress.com?a1=1&a2=2&a3=3');

The &a2=2&a3=3 part was actually part of the /Default/Details URL, not the http://www.someaddress.com one. Now that the inner URL is URI encoded, it should work.

Make sure to decode the value when using the url parameter though, using decodeURIComponent:

var urlMatch = location.search.match(/url=(.*)&?/);
if (urlMatch) {
    var decodedUrl = decodeURIComponent(urlMatch[1]);
    // do something with the decoded URL...
}

EDIT

For the first part (URI encoding) and based on your code, you should use it this way:

<div>
    <input type="button" value="test" id="btnTest" />
</div>

<script>
    var vurl = '@Url.Action("Details", "Default")';
    $(function () {
        $("#btnTest").click(function () {
            var url = "http://www.someaddress.com?a1=1&a2=2&a3=3";
            vurl = vurl + encodeURIComponent(url);
            window.open(vurl);

        });
    })

</script>

As for the ASP.NET part and the use of the string url parameter, I'd suggest checking the following post: using decodeURIComponent within asp.net as I'm not familiar with this environment.