This question already has answers here:
Response.Redirect to new window
(20 answers)
Closed 7 years ago.
I am writing a project using ASP.NET C#.
I want to implement linkbutton click event to open new page in a new tab, but before I have to create new session variable. I have tried this:
protected void LinkButton_Click3(Object sender, EventArgs e)
{
string p_id = (sender as LinkButton).CommandArgument;
Session["p_id"] = p_id;
Response.Write("<script type='text/javascript'> window.open('details.aspx','_blank'); </script>");
}
But it doesn't work anyway.
Based on your comments, you should disable your popup blocker.
Try this, call this function on button click or document.ready only on page where you want to redirect from.
<script type="text/javascript">
function newTab()
{
if (opener.document.getElementById("aspnetForm").target != "_blank") return;
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = opener.location.href;
}
</script
or add this to linkbutton html
OnClientClick="aspnetForm.target ='_blank';"
Sometimes it works for me to just declare whatever I would invoke dynamically from the administrated code into a javascript function and just call it from within with the
RegisterClientScriptBlock method in ClientScript class:
Daclare the window.open function:
<script type="text/javascript">
function SetRedirect(URI) {
window.open(URI, "Details", "menubar=no, location=no, resizable=yes, scrollbars=yes, status=yes, width = 1200, height = 600");
}
</script>
And from within the code behind class just a gateway caller to this function like:
void MessageGateway(string URI)
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"logCallBack", #"<script type=""text/javascript"">SetRedirect('" + URI + "');</script>");
}
And that's it, you may call this gateway with your stuff as normally you do,
MessageGateway(string.Format("../IRMQueryPO.aspx?id={0}", e.Item.Cells[2].Text));
You can try tweeking the "target" parameter with "_blank" in order to open a tab instead a window, it's just a matter of the flavor your solution points in.
Related
Warning: I am a novice when it comes to ASP and javascript - I'm more used to desktop apps. Web development is completely new to me.
I have inherited an ASP.net project that I need to keep up-to-date.
My current problem is that I need to display the client time in a text control (label or literal control - doesn't have to specifically be one of those, I just need to show it in text) when the user has clicked a button to 'Save'. If I do it server-side, in the 'SaveChanges' function, I get the time of where the server is.
My button is defined as below:
<asp:Button ID="Save" runat="server" Text="Save Changes" OnClick="SaveChanges"
ValidationGroup="ProjectSummaryValidationGroup"
meta:resourcekey="SaveResource1" />
And my Literal/Label is:
<asp:Label ID="SaveTime" runat="server"></asp:Label>
I have found a javascript function to calculate the client time from one of the other questions on here: (EDIT: I have updated this function so that the text value of my label is being assigned a value)
<script type="text/javascript">
function GetDate(date) {
CurTime = new Date(date);
var offset = (new Date().getTimezoneOffset() / 60) * (-1);
var utc = CurTime.getTime() + (offset * 60000 * (-1));
var serverDate = new Date(utc + (3600000 * offset));
var dateString = (serverDate.getMonth() + 1) + "/" + serverDate.getDate() + "/" +
serverDate.getFullYear() + " " + serverDate.toLocaleTimeString("en-US", { hour12: true });
document.getElementById('<%=SaveTime.ClientID%>').Text = dateString;
}
</script>
My problem is I don't know where to put this javascript function in my apsx page, or how to set the Text value of my label to the date string calculated in the function. I don't even know for sure how to 'call' this function...
So my questions are:
Where do I have to define the javascript function?
How to I 'call' this javascript function when the user clicks the 'Save' button, so that the text one my age is updated?
You can use Java Script Function like
<script type="text/javascript" language="javascript">
function javascriptFunction()
{
}
</script>
call this function
If you Used Update Panels Then You can Use in .Cs Page:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);
or On Button's Click in .aspx page
<asp:Button ID="Save" runat="server" Text="Save Changes" OnClick="SaveChanges"
onClientClick="javascriptFunction();"
ValidationGroup="ProjectSummaryValidationGroup"
meta:resourcekey="SaveResource1" />
Other Wise You can Use in .cs page
ClientScript.RegisterStartupScript
(GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);
set value of Label in javascript:
document.getElementById('<%=SaveTime.ClientID%>').value = "Your Date";
for label :
void Page_Load(object sender, EventArgs e)
{
lblMyLabel.Attributes.Add("onclick",
"javascript:alert('ALERT ALERT!!!')");
}
I have read many posts here and many other sites and so I've gathered a few versions of HOW to do this. My problem is that I can't get it to do anything.
Here's the Javascript, just an alert for testing:
<script type="text/javascript">
function ICDcheck() {
alert('Patient has an ineligible diagnosis code!');
}
</script>
I tested this manually by adding the function to an OnClientClick of a button and it worked fine.
Here is what I've tried in the codebehind:
ClientScript.RegisterClientScriptBlock(this.GetType(), "uniqueKey", "ICDcheck()", true);
and...
string jsMethodName = "ICDcheck()";
ScriptManager.RegisterClientScriptBlock(this, typeof(string), "uniqueKey", jsMethodName, true);
and...
lblJavaScript.Text = "<script type='text/javascript'>ICDcheck();</script>";
This last one references a label I have sitting at the top of my asp : Content just below a script and the asp : ScriptManager block.
I've placed these bits in the button_click, the page_load, the sqldatasource_selecting, the formview_PageIndexChanging and always the same, nothing.
As always, thanks for your patience and help. My ignorance will likely be exposed as the problem, but I'm learning.
Try using Page.ClientScript :
Page.ClientScript.RegisterStartupScript( GetType(), "MyKey", "ICDcheck();", true);
Also install firebug and check if there are any script errors.
Try this. On your page, have a button:
<asp:Button ID="RunJsButton" runat="server" Text="Button" />
Then, in the code-behind, inject the script into the response and add the wireup to the button:
protected void Page_Load(object sender, EventArgs e)
{
string scriptToRun = #"function ICDcheck() { alert('Patient has an ineligible diagnosis code!');}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "", scriptToRun, true);
RunJsButton.OnClientClick = "return ICDcheck();";
}
If that is the kind of thing you are after, you can refactor it a bit to implement best practice.
Try
<button ID="your_btn" onclick="javascript:your_function(); return false;"><asp:literal ID="your_literal" runat="server" /></button>
and
<script type="text/javascript">
function your_function() {
alert('Patient has an ineligible diagnosis code!');
}
</script>
This should work.
string jsToRun = "<script language=javascript>ICDcheck();</script>";
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Key", jsToRun);
I am registering java script to my Asp.net code behind file, which is working fine. Now, I have some update panels on the same page and problem is whenever there is any change in any of the update panel, this script is automatically getting called. Is there any way that I can stop this happening. I can't remove update panels from my page and this script is also a very essential part of the application. In this situation I am just calling a alert (rad alert with set time out functionality) when Save Button is clicked or an Update routine is called while I have few other buttons in update panels and whenver any of the button which is registered to the update panels clicked, the following script is called un-willingly. Anyone's help will really be appreciated.
following is my Page.ClientScript
string radalertscript = "<script language='javascript'> Sys.Application.add_load(function(sender, e) {var oWnd = radalert('dialogMessage', 400, 140, 'Saved');window.setTimeout(function () { oWnd.Close(); }, 3000);});</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", radalertscript);
You can assign empty string to same key radalert to remove the script.
if(some_condition)
Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", "");
Edit: Based on comments, you can make it simple without using RegisterStartupScript
In code behind
btnSave.Attributes.Add("", "saveButtonFunction();");
In Javascript
<script language='javascript'>
Sys.Application.add_load(function(sender, e) {
if(btnSaveClicked){
var oWnd = radalert('dialogMessage', 400,140, 'Saved');
window.setTimeout(function () { oWnd.Close(); }, 3000);
btnSaveClicked = false;
}
});
btnSaveClicked = false;
function saveButtonFunction(){
btnSaveClicked = true;
};
</script>
Thank you very much for your answer Adil. I already have followed the same approach with little difference. I have taken JavaScript out from my code behind file and have registered Sys.Application.add_load event as follow
Sys.Application.add_load(DisplayRadAlertHandler);
function DisplayRadAlertHandler() {
var getMessage = document.getElementById('<%=radAlertDialogHidden.ClientID%>').value;
if (getMessage != "") {
document.getElementById('<%=radAlertDialogHidden.ClientID%>').value = "";
var oWnd = radalert(getMessage, 400, 140, 'Saved');
window.setTimeout(function () { oWnd.Close(); }, 3000);
}
}
Here I am setting my alert message in a hidden input field from code behind file and in the above event handler I am just checking if message is there than reset the hidden field and display the message. Your approach is also right and I have marked your answer but as I am displaying my message from multiple locations (Save button, Update routine etc.) so by assigning value to hidden input field and than resetting in above event handler looks more appropriate. Thanks once again for your help.
I am having what I believe should be a fairly simple problem, but for the life of me I cannot see my problem. The problem is related to ScriptManager.RegisterStartupScript, something I have used many times before.
The scenario I have is that I have a custom web control that has been inserted into a page. The control (and one or two others) are nested inside an UpdatePanel. They are inserted onto the page onto a PlaceHolder:
<asp:UpdatePanel ID="pnlAjax" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="placeholder" runat="server">
</asp:PlaceHolder>
...
protected override void OnInit(EventArgs e){
placeholder.Controls.Add(Factory.CreateControl());
base.OnInit(e);
}
This is the only update panel on the page.
The control requires some initial javascript be run for it to work correctly. The control calls:
ScriptManager.RegisterStartupScript(this, GetType(),
Guid.NewGuid().ToString(), script, true);
and I have also tried:
ScriptManager.RegisterStartupScript(Page, Page.GetType(),
Guid.NewGuid().ToString(), script, true);
The problem is that the script runs correctly when the page is first displayed, but does not re-run after a partial postback. I have tried the following:
Calling RegisterStartupScript from CreateChildControls
Calling RegisterStartupScript from OnLoad / OnPreRender
Using different combinations of parameters for the first two parameters (in the example above the Control is Page and Type is GetType(), but I have tried using the control itself, etc).
I have tried using persistent and new ids (not that I believe this should have a major impact either way).
I have used a few breakpoints and so have verified that the Register line is being called correctly.
The only thing I have not tried is using the UpdatePanel itself as the Control and Type, as I do not believe the control should be aware of the update panel (and in any case there does not seem to be a good way of getting the update panel?).
Can anyone see what I might be doing wrong in the above?
Thanks :)
Well, to answer the query above - it does appear as if the placeholder somehow messes up the ScriptManager.RegisterStartupScript.
When I pull the control out of the placeholder and code it directly onto the page the Register script works correctly (I am also using the control itself as a parameter).
ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), script, true);
Can anyone throw any light on why an injected control onto a PlaceHolder would prevent the ScriptManager from correctly registering the script? I am guessing this might have something to do with the lifecycle of dynamic controls, but would appreciate (for my own knowledge) if there is a correct process for the above.
I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel, and the scriptmanager is on the usercontrol.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
I think you should indeed be using the Control overload of the RegisterStartupScript.
I've tried the following code in a server control:
[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
protected override void OnInit(EventArgs e){
base.OnInit(e);
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
Then in my page I have:
protected override void OnInit(EventArgs e){
base.OnInit(e);
Placeholder1.Controls.Add(new AlertControl());
}
Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.
This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.
The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:
Sys.WebForms.PageRequestManager.getInstance()
.add_endRequest(EndRequestHandler);
The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.
My only other questions are:
What is your script actually doing?
Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
Have you tried Firefox and Firebug - is that reporting any script errors?
When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.
I use this in the updatepanel_prerender event:
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
"<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
"include('yourDynamic.js');" & _
"removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
, False)
In the page or in some other include you will need this javascript:
// Include a javascript file inside another one.
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('src'))
{
if(scripts[x].getAttribute('src').indexOf(filename) != -1)
{
head.removeChild(scripts[x]);
break;
}
}
}
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('id'))
{
if(scripts[x].getAttribute('id').indexOf(id) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
var knowJunk = 'Sys.Application.add_init(function() {';
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].textContent)
{
if(scripts[x].textContent.indexOf(knowJunk) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
}
Pretty cool, ah...jejeje
This part of what i posted some time ago here.
Hope this help... :)
I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.
A similar solution might work for you.
DO NOT Use GUID For Key
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel)
Guid.NewGuid().ToString(), myScript, true);
and if you want to do that , call Something Like this function
public static string GetGuidClear(string x)
{
return x.Replace("-", "").Replace("0", "").Replace("1", "")
.Replace("2", "").Replace("3", "").Replace("4", "")
.Replace("5", "").Replace("6", "").Replace("7", "")
.Replace("8", "").Replace("9", "");
}
What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);
Sometimes it doesnt fire when the script has some syntax error, make sure the script and javascript syntax is correct.
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),script, true );
The "true" param value at the end of the ScriptManager.RegisterStartupScript will add a JavaScript tag inside your page:
<script language='javascript' defer='defer'>your script</script >
If the value will be "false" it will inject only the script witout the --script-- tag.
I try many things and finally found that the last parameter must be false and you must add <SCRIPT> tag to the java script :
string script = "< SCRIPT >alert('hello!');< /SCRIPT>";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), key, script, **false**);
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?
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()">
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");
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);
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>");
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 = '';
}
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);
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?
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();"/>
<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/
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;";
}
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.
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 ());
}
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','');
}
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>
You may want to use the Page.RegisterStartupScript to ensure that the javascript fires on page load.
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);
}
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.
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.
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)
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);