I want to do a Response.Redirect(\"MyPage.aspx\")
but have it open in a new browser window. I\'ve done this before without using the JavaScript register script method. I just can\'t remember how?
问题:
回答1:
I just found the answer and it works :)
You need to add the following to your server side link/button:
OnClientClick=\"aspnetForm.target =\'_blank\';\"
My entire button code looks something like:
<asp:LinkButton ID=\"myButton\" runat=\"server\" Text=\"Click Me!\"
OnClick=\"myButton_Click\"
OnClientClick=\"aspnetForm.target =\'_blank\';\"/>
In the server side OnClick I do a Response.Redirect(\"MyPage.aspx\");
and the page is opened in a new window.
The other part you need to add is to fix the form\'s target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.
<script type=\"text/javascript\">
function fixform() {
if (opener.document.getElementById(\"aspnetForm\").target != \"_blank\") return;
opener.document.getElementById(\"aspnetForm\").target = \"\";
opener.document.getElementById(\"aspnetForm\").action = opener.location.href;
}
</script>
and
<body onload=\"fixform()\">
回答2:
You can use this as extension method
public static class ResponseHelper
{
public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures)
{
if ((String.IsNullOrEmpty(target) || target.Equals(\"_self\", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures))
{
response.Redirect(url);
}
else
{
Page page = (Page)HttpContext.Current.Handler;
if (page == null)
{
throw new InvalidOperationException(\"Cannot redirect to new window outside Page context.\");
}
url = page.ResolveClientUrl(url);
string script;
if (!String.IsNullOrEmpty(windowFeatures))
{
script = @\"window.open(\"\"{0}\"\", \"\"{1}\"\", \"\"{2}\"\");\";
}
else
{
script = @\"window.open(\"\"{0}\"\", \"\"{1}\"\");\";
}
script = String.Format(script, url, target, windowFeatures);
ScriptManager.RegisterStartupScript(page, typeof(Page), \"Redirect\", script, true);
}
}
}
With this you get nice override on the actual Response object
Response.Redirect(redirectURL, \"_blank\", \"menubar=0,scrollbars=1,width=780,height=900,top=10\");
回答3:
Because Response.Redirect is initiated on the server you can\'t do it using that.
If you can write directly to the Response stream you could try something like:
response.write(\"<script>\");
response.write(\"window.open(\'page.html\',\'_blank\')\");
response.write(\"</script>\");
回答4:
Contruct your url via click event handler:
string strUrl = \"/some/url/path\" + myvar;
Then:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), \"popup\", \"window.open(\'\" + strUrl + \"\',\'_blank\')\", true);
回答5:
The fixform trick is neat, but:
You may not have access to the code of what loads in the new window.
Even if you do, you are depending on the fact that it always loads, error free.
And you are depending on the fact that the user won\'t click another button before the other page gets a chance to load and run fixform.
I would suggest doing this instead:
OnClientClick=\"aspnetForm.target =\'_blank\';setTimeout(\'fixform()\', 500);\"
And set up fixform on the same page, looking like this:
function fixform() {
document.getElementById(\"aspnetForm\").target = \'\';
}
回答6:
You can also use in code behind like this way
ClientScript.RegisterStartupScript(this.Page.GetType(), \"\",
\"window.open(\'page.aspx\',\'Graph\',\'height=400,width=500\');\", true);
回答7:
This is not possible with Response.Redirect as it happens on the server side and cannot direct your browser to take that action. What would be left in the initial window? A blank page?
回答8:
popup method will give a secure question to visitor..
here is my simple solution: and working everyhere.
<script type=\"text/javascript\">
function targetMeBlank() {
document.forms[0].target = \"_blank\";
}
</script>
<asp:linkbutton runat=\"server\" ID=\"lnkbtn1\" Text=\"target me to blank dude\" OnClick=\"lnkbtn1_Click\" OnClientClick=\"targetMeBlank();\"/>
回答9:
<asp:Button ID=\"btnNewEntry\" runat=\"Server\" CssClass=\"button\" Text=\"New Entry\"
OnClick=\"btnNewEntry_Click\" OnClientClick=\"aspnetForm.target =\'_blank\';\"/>
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.Redirect(\"New.aspx\");
}
Source: http://dotnetchris.wordpress.com/2008/11/04/c-aspnet-responseredirect-open-into-new-window/
回答10:
If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:
protected void MyButton_OnPreRender(object sender, EventArgs e)
{
string URL = \"~/MyPage.aspx\";
URL = Page.ResolveClientUrl(URL);
MyButton.OnClientClick = \"window.open(\'\" + URL + \"\'); return false;\";
}
回答11:
You can also use the following code to open new page in new tab.
<asp:Button ID=\"Button1\" runat=\"server\" Text=\"Go\"
OnClientClick=\"window.open(\'yourPage.aspx\');return false;\"
onclick=\"Button3_Click\" />
And just call Response.Redirect(\"yourPage.aspx\"); behind button event.
回答12:
I always use this code... Use this code
String clientScriptName = \"ButtonClickScript\";
Type clientScriptType = this.GetType ();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager clientScript = Page.ClientScript;
// Check to see if the client script is already registered.
if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
{
StringBuilder sb = new StringBuilder ();
sb.Append (\"<script type=\'text/javascript\'>\");
sb.Append (\"window.open(\' \" + url + \"\')\"); //URL = where you want to redirect.
sb.Append (\"</script>\");
clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());
}
回答13:
Here\'s a jQuery version based on the answer by @takrl and @tom above. Note: no hardcoded formid (named aspnetForm above) and also does not use direct form.target references which Firefox may find problematic:
<asp:Button ID=\"btnSubmit\" OnClientClick=\"openNewWin();\" Text=\"Submit\" OnClick=\"btn_OnClick\" runat=\"server\"/>
Then in your js file referenced on the SAME page:
function openNewWin () {
$(\'form\').attr(\'target\',\'_blank\');
setTimeout(\'resetFormTarget()\', 500);
}
function resetFormTarget(){
$(\'form\').attr(\'target\',\'\');
}
回答14:
I used Hyperlink instead of LinkButton and it worked just fine, it has the Target property so it solved my problem. There was the solution with Response.Write but that was messing up my layout, and the one with ScriptManager, at every refresh or back was reopening the window. So this is how I solved it:
<asp:HyperLink CssClass=\"hlk11\" ID=\"hlkLink\" runat=\"server\" Text=\'<%# Eval(\"LinkText\") %>\' Visible=\'<%# !(bool)Eval(\"IsDocument\") %>\' Target=\"_blank\" NavigateUrl=\'<%# Eval(\"WebAddress\") %>\'></asp:HyperLink>
回答15:
You may want to use the Page.RegisterStartupScript to ensure that the javascript fires on page load.
回答16:
you can open new window from asp.net code behind using ajax like I did here http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectionChanged += CalendarSelectionChanged;
}
private void CalendarSelectionChanged(object sender, EventArgs e)
{
DateTime selectedDate = ((Calendar) sender).SelectedDate;
string url = \"HistoryRates.aspx?date=\"
+ HttpUtility.UrlEncode(selectedDate.ToShortDateString());
ScriptManager.RegisterClientScriptBlock(this, GetType(),
\"rates\" + selectedDate, \"openWindow(\'\" + url + \"\');\", true);
}
回答17:
None of the previous examples worked for me, so I decided to post my solution. In the button click events, here is the code behind.
Dim URL As String = \"http://www.google/?Search=\" + txtExample.Text.ToString
URL = Page.ResolveClientUrl(URL)
btnSearch.OnClientClick = \"window.open(\'\" + URL + \"\'); return false;\"
I was having to modify someone else\'s response.redirect code to open in a new browser.
回答18:
I used this approach, it doesn\'t require you to do anything on the popup (which I didn\'t have access to because I was redirecting to a PDF file). It also uses classes.
$(function () {
//--- setup click event for elements that use a response.redirect in code behind but should open in a new window
$(\".new-window\").on(\"click\", function () {
//--- change the form\'s target
$(\"#aspnetForm\").prop(\"target\", \"_blank\");
//--- change the target back after the window has opened
setTimeout(function () {
$(\"#aspnetForm\").prop(\"target\", \"\");
}, 1);
});
});
To use, add the class \"new-window\" to any element. You do not need to add anything to the body tag. This function sets up the new window and fixes it in the same function.
回答19:
I did this by putting target=\"_blank\" in the linkbutton
<asp:LinkButton ID=\"btn\" runat=\"server\" CausesValidation=\"false\" Text=\"Print\" Visible=\"false\" target=\"_blank\" />
then in the codebehind pageload just set the href attribute:
btn.Attributes(\"href\") = String.Format(ResolveUrl(\"~/\") + \"test/TestForm.aspx?formId={0}\", formId)
回答20:
HTML
<asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" onclick=\"Button1_Click\" OnClientClick = \"SetTarget();\" />
Javascript:
function SetTarget() {
document.forms[0].target = \"_blank\";}
AND codebehind:
Response.Redirect(URL);