Click here to Skip to main content
15,907,906 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a method (in C#) that needs to open a URL in the same window, but instead it opens the url in a new tab
public static void OpenSameWindow(string url)
    {
        string cmd = @"<script>window.open('{0}','_self',false);</script>";
        System.Web.HttpContext.Current.Response.Write(string.Format(cmd, url));
    }


Everything I have read indicates that this is the correct solution, but it always opens in a new tab. Any thoughts?

What I have tried:

Response.Redirect("somepage.aspx",true);

rver.Transfer("somepage.aspx");
Posted
Updated 12-Jul-18 14:48pm
Comments
F-ES Sitecore 12-Jul-18 8:40am    
Response.Redirect should work. If it doesn't then there is something about your code you're not telling us such that it's being called by ajax or something like that.
RmcbainTheThird 12-Jul-18 10:39am    
That is what I thought as well. It is all in the code behind ... no ajax no JS of any kind
protected void MenuClick(object sender, System.EventArgs e)
{
Button clickedButton = (Button) sender;
//Response.Redirect(clickedButton.CommandArgument,true);
// WebUtilities.OpenSameWindow(clickedButton.CommandArgument);


//Server.Transfer(clickedButton.CommandArgument);
}

public static void OpenSameWindow(string url)
{
string cmd = @"window.open('{0}','_self',false);";

System.Web.HttpContext.Current.Response.Write(string.Format(cmd, url));
}
RmcbainTheThird 17-Jul-18 16:14pm    
And indeed it was programmer error :) found in the head of my aspx file: <base target="_blank"/>

1 solution

As mentioned, Response.Redirect should work if you just want to navigate to the same window page.

The ASP.NET Button server control will render as type="submit".Invoking the OnClick event will submit the form, and result a page reload, which clashes with your attempt using window.open with _self. You can just add a type="button" attribute to the button to prevent that. Alternatively, you might want to consider using window.location.href instead: JavaScript Window Location[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900