views:

148

answers:

1

Through JavaScript I am appending one query parameter to the page url and I am facing one strange behaiviour.

<div>
    <a href="Default3.aspx?id=2">Click me</a>
</div>


$(function () {
    window.location.href = window.location.href + "&q=" + "aa";
});

Now I am appending &q=aa in default3.aspx and in this page the &q=aa is getting added continuously, causing the URL to become:

 http://localhost:1112/WebSite2/Default3.aspx?id=2&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa&amp;q=aa

One would say just pass it like <a href="Default3.aspx?id=2&q=aa">Click me</a>, but I cant do that. The value of this query parameter is actually the value of an HTML element which is in default3.aspx. I have to add it in runtime.

What are the ways to achieve this?

+5  A: 

The reason this happens is because if you change the window.location value the browser will perform a redirect to the new location and as you are doing this in the document.ready this happens indefinitely.

Before doing this redirect you might want to check if the current url already contains these parameters.

$(function () {
    var suffix = '&q=aa';
    var currentUrl = window.location.href;
    if (currentUrl.match(suffix + '$') != suffix) {
        window.location.href = window.location.href + suffix;
    }
});

Remark: Using javascript for this purpose seems to me like a bad idea. I would perform this redirect on the server side which would be more reliable. In your default.aspx page:

protected void Page_Load(object sender, EventArgs e) 
{
    var q = Request["q"];
    if (string.IsNullOrEmpty(q))
    {
        // q parameter has not been set => redirect
        Response.Redirect("/default.aspx?q=aa");
    }
}
Darin Dimitrov
@Darin - can u pls explain if (currentUrl.match(suffix + '$') != suffix) { i mean why the $ sign ? Thanks for all ur help
Wondering
Mark
Mark
@Darin -True.very true.The flow.architecture is totally wrong, actually this is enhancement, so cant help it. Thanks.
Wondering
@Mark- Thnx for ur help.
Wondering