Reputation: 2587
I’m trying to use a button click to open a page in a new tab/window. I’ve looked at solutions similar to this, but the answers given there are either to use a link or have it open in the same window. I need to use a button because it needs to generate the link based on criteria data entered in the form (string manipulation). This button is not submitting the form though; it’s just validating some of the data on an external site. I need this in a different window or tab so they can go back and forth between my form and the validation site. This is basically my current Button_Click
event:
var Address = AddressTextbox.Text.Trim();
Address = Address.Replace(' ', '+');
var Url = "http://www.example.com/query?text=" + Address + "¶m1=foo¶m2=bar";
Response.Redirect(Url);
This works except that Response.Redirect(Url)
only opens in the same window, not a new one.
Upvotes: 0
Views: 26370
Reputation: 46047
Use the OnClientClick
attribute:
<script type="text/javascript">
redirectToPage = function(url){
void(window.open(url, "child_window"));
return false;
}
</script>
<asp:Button ID="Button1" runat="server"
Text="Click Me!"
OnClientClick="return redirectToPage('/somefolder/somepage.aspx');" />
Using the OnClientClick
attribute, it's important to remember to return false
at the end, otherwise the button click will trigger a postback.
EDIT
If you want to open a new window from the click event handler, you can do something like this:
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "open_window",
string.Format("void(window.open('{0}', 'child_window'));", "/somefolder/somepage.aspx"), true);
}
Admittedly, this is kind of ugly, but if there's certain information that you won't have until the button click logic is executed, this might be your best option. If there's any way you can build the URL before the button is clicked, you can just assign the OnClientClick
in code-behind.
Upvotes: 3
Reputation: 63966
Just spit out javascript code from the Click event handler on the Button.
var Address = AddressTextbox.Text.Trim();
Address = Address.Replace(' ', '+');
var Url = "http://www.example.com/query?text=" + Address + "¶m1=foo¶m2=bar";
Page.ClientScript.RegisterStartupScript(this.GetType(), "dsadas", "window.open('"+Url+"');", true);
Upvotes: 6