C# Study 2

ASP.Net Response.Redirect or Server.Transfer: Open New Tab from Code Behind

"time2"

Thus with the help of JavaScript we can set the target property of form to _blank whenever we want to open the page in a new window. Refer below

I have an ASP.Net Button

1
2
3
4
5
Aspx

<asp:Button ID="Button1" runat="server" Text="Button"

onclick="Button1_Click" OnClientClick = "SetTarget();" />

I am calling the SetTarget() JavaScript function OnClientClick event of the ASP.Net Button Control as described below

1
2
3
4
5
6
7
8
9
10
JavaScript

<script type = "text/javascript">

function SetTarget() {

document.forms[0].target = "_blank";
}

</script>

As you can see above I am setting the target property of the HTML FORM to _blank

Secondly I am calling the Button1_Click method OnClick event Control as described below

1
2
3
4
5
6
7
C#

protected void Button1_Click(object sender, EventArgs e)

{
Response.Redirect("page2.aspx");
}
1
2
3
4
5
6
7
VB.Net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Response.Redirect("Page2.aspx")

End Sub

Thus now when you click on the Button, the JavaScript function sets the target property of the form is to _blank Thus when PostBack occurs it first opens the current page in new window and then executes the Response.Redirect method thus helping us achieve our goal.

Same way we can use Server.Transfer on the Button Click event

1
2
3
4
5
6
C#

protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("page2.aspx");
}
1
2
3
4
5
6
VB.Net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Server.Transfer("Page2.aspx")
End Sub
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%