Response.Redirect to new window - c#

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);

Related

Asp.net: Response.Write OnServerClick codebehind function not working

I'm trying to make it so if your Session["LoggedIn"] is true, the wuc (Web User Control, which is the Navbar and is connected to the MasterPage which is connected to the page) prints a logout button.
so I have it like this:
Response.Write("<a runat='server' ID='lblLogout' class='nav-link' CausesValidation='False' OnServerClick='lblLogout_Click'>Logout</a>");
the CodeBehind function looks like this:
protected void lblLogout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Session["LoggedIn"] = false;
Session["IsAdmin"] = false;
Session["Username"] = "";
}
now, I've tried everything, if I use response.write like that, I can't click it, it just doesn't fire or do anything, if I don't use it inside Response.Write, it does work..
I even tried prinitng an asp:LinkButton instead to see if that works, but it doesn't print out anything when I use it like:
Response.Write("<asp:LinkButton class='nav-link' runat='server' ID='lblLogout' Text='Logout' CausesValidation='False' OnClick='lblLogout_Click' />");
Now the solution that I found was putting another page for logout and placing the function on PageLoad, which works, but I'm wondering if I can make it work so I can use the function from CodeBehind, instead of having to go to another page.
my working solution:
if ((bool)Session["LoggedIn"] == true)
{
Response.Write("<li class='nav-item'> <a runat='server' ID='lblLogout' class='nav-link' CausesValidation='False' href='../PagesForVisitor/wfLogout.aspx'>Logout</a></li><li><a class='navbar-brand' href='#'><img src='" + GetSource() + "' width = '30' height = '30' alt = ''/ ></a></li>");
}
(this one prints out a profile pic as well)
p.s using Bootstrap for styling, not sure if that matters, thanks a bunch..
You should use
<asp:Button id='' runat='server'>
tag
or use css to custom the button look depending on the style.
You can make it a hyperlink in the properties.

Can't get Javascript to fire from c# codebehind

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);

Asp .net Linkbutton child controls dissapears on postback

I have an asp .net hyperlink control declared like this:
<li runat="server" id="liveChatCtrl" Visible="false"><asp:LinkButton runat="server" ID="hlnkLiveChat" CausesValidation="false" OnClick="hlnkLiveChat_Click">Live Chat Support <i class="icon icon_next_03 fr"></i><i runat="server" id="iconChat" class="icon_chat_online"></i></asp:LinkButton></li>
My problem is that the contents of the linkbutton disappears on postback. Any ideas why this is happening?
On load I execute the following code on the linkbutton or it's children:
string absoluteURL = UtilManager.Settings.Item(Utils.BrandID, "URL:absoluteURL");
string chatLink = "StartChat.aspx";
if (HttpContext.Current.User.Identity.IsAuthenticated)
chatLink = "LiveChat.aspx";//~/
//else
// chatLink = "SalesChat.aspx";
string link = absoluteURL + chatLink;
hlnkLiveChat.Attributes["onclick"] = string.Format("javascript:window.open( '{0}', 'chat', 'status=no,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes,height=505,width=420,left=30,top=30');", link);//"openPopup('" + link + "','chat'); return false;";
liveChatCtrl.Visible = true;
A guess...
I believe you may have the code in your Page_Load (or Init) inside an if(!IsPostBack)
If this is the case, move it outside of this if statement as you need it to run as your default visible for your liveChatCtrl is false
Either that or re-code a little so that your default visible is true and you run a check on postback to hide it if needed.

Client-side validation is not firing on my custom BaseValidator

So, I'm writing a custom validator to validate the Ajax Toolkit's Rating control. The client side validation isn't firing, though.
I have this method to register the script:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string script = #"<script type=""text/javascript"">function RatingValidatorEvaluateIsValid(val)
{
alert( 'here' );
return false;
}</script> ";
Page.ClientScript.RegisterClientScriptBlock(GetType(), "ratingValidator", script);
}
And I register the attribute like this:
protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
// Add the client-side code (if needed)
if (this.RenderUplevel)
{
writer.AddAttribute("evaluationfunction", "RatingValidatorEvaluateIsValid", false);
}
}
The script appears on the page, as well as the attribute, but the alert('here') never appears.
(Everything works fine, Server-side)
Edit Markup:
<ajaxToolkit:Rating ID="ajaxRating" runat="server" StarCssClass="ratingStar" WaitingStarCssClass="savedRatingStar"
FilledStarCssClass="filledRatingStar" EmptyStarCssClass="emptyRatingStar" CssClass="stars"
RatingAlign="Horizontal" RatingDirection="LeftToRightTopToBottom"
AutoPostBack="True" OnChanged="OnChanged" />
<my:RatingValidator runat="server" ID="RatingValidator" ControlToValidate="ajaxRating"
ErrorMessage="Please select a rating." EnableClientScript="True"
</my:RatingValidator>
Edit 2 Okay, this is weird...
The span that gets generated is proper:
<span id="CPHUser_rating_RatingValidator" evaluationfunction="RatingValidatorEvaluateIsValid" style="visibility:hidden;">Please select a rating.</span>
But the JS at the bottom doesn't have my evaluationfunction assigned.
var CPHUser_rating_RatingValidator = document.all ? document.all["CPHUser_rating_RatingValidator"] : document.getElementById("CPHUser_rating_RatingValidator");
CPHUser_rating_RatingValidator.controltovalidate = "CPHUser_rating_ajaxRating";
CPHUser_rating_RatingValidator.errormessage = "Please select a rating.";
Looks like I answered my own question...
I was apparently assigning my evaluationfunction incorrectly.
I've changed it to this:
Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "RatingValidatorEvaluateIsValid");
and now it works.
Thanks for your help, guys!

ASP.Net double-click problem

having a slight problem with an ASP.net page of mine. If a user were to double click on a "submit" button it will write to the database twice (i.e. carry out the 'onclick' method on the imagebutton twice)
How can I make it so that if a user clicks on the imagebutton, just the imagebutton is disabled?
I've tried:
<asp:ImageButton
runat="server"
ID="VerifyStepContinue"
ImageUrl=image src
ToolTip="Go"
TabIndex="98"
CausesValidation="true"
OnClick="methodName"
OnClientClick="this.disabled = true;" />
But this OnClientClick property completely stops the page from being submitted! Any help?
Sorry, yes, I do have Validation controls... hence the icky problem.
Working on this still, up to this point now:
ASP code:
<asp:TextBox ID="hidToken" runat="server" Visible="False" Enabled="False"></asp:TextBox>
...
<asp:ImageButton runat="server" ID="InputStepContinue" Name="InputStepContinue" ImageUrl="imagesrc" ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="SubmitMethod" OnClientClick="document.getElementById('InputStepContinue').style.visibility='hidden';" />
C# code:
private Random
random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
//Use a Token to make sure it has only been clicked once.
if (Page.IsPostBack)
{
if (double.Parse(hidToken.Text) == ((double)Session["NextToken"]))
{
InputMethod();
}
else
{
// double click
}
}
double next = random.Next();
hidToken.Text = next + "";
Session["NextToken"] = next;
Actually... this nearly works. The double click problem is pretty much fixed (yay!) The image still isn't hidden though.
The general approach is twofold.
Serverside:
On load of the page, generate a token (using System.Random), save it in the session, and write it to a hidden form field
On submit, check that the hidden form field equals the session variable (before setting it again)
Do work
Clientside:
Similar to what you have, but probably just hide the button, and replace it with some text like 'submitting'.
The important thing to note, client side, is that the user may cancel the post by hitting 'escape', so you should consider what to do here (depending on how far along they are the token won't be used, so you'll need to bring the button back from being disabled/hidden).
Complete example follows:
C# (includes code to see it in action):
<html>
<head runat="server">
<title>double-click test</title>
<script language="c#" runat="server">
private Random
random = new Random();
private static int
TEST = 0;
public void Page_Load (object sender, EventArgs ea)
{
SetToken();
}
private void btnTest_Click (object sender, EventArgs ea)
{
if( IsTokenValid() ){
DoWork();
} else {
// double click
ltlResult.Text = "double click!";
}
}
private bool IsTokenValid ()
{
bool result = double.Parse(hidToken.Value) == ((double) Session["NextToken"]);
SetToken();
return result;
}
private void SetToken ()
{
double next = random.Next();
hidToken.Value = next + "";
Session["NextToken"] = next;
}
private void DoWork ()
{
TEST++;
ltlResult.Text = "DoWork(): " + TEST + ".";
}
</script>
</head>
<body>
<script language="javascript">
var last = null;
function f (obj)
{
obj.src = "http://www.gravatar.com/avatar/4659883ec420f39723c3df6ed99971b9?s=32&d=identicon&r=PG";
// Note: Disabling it here produced strange results. More investigation required.
last = obj;
setTimeout("reset()", 1 * 1000);
return true;
}
function reset ()
{
last.src = "http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG";
last.disabled = "false";
}
</script>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="hidToken" />
<asp:ImageButton runat="server" ID="btnTest"
OnClientClick="return f(this);"
ImageUrl="http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG" OnClick="btnTest_Click" />
<pre>Result: <asp:Literal runat="server" ID="ltlResult" /></pre>
</form>
</body>
</html>
If you have validation on the page, disabling the button client side gets a little tricky. If validation fails, you don't want to disable the button. Here's a snippet that adds the client side event handler:
private void BuildClickOnceButton(WebControl ctl)
{
System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
sbValid.Append(ctl.ClientID + ".value = 'Please wait...';");
sbValid.Append(ctl.ClientID + ".disabled = true;");
// GetPostBackEventReference obtains a reference to a client-side script
// function that causes the server to post back to the page.
sbValid.Append(ClientScript.GetPostBackEventReference(ctl, ""));
sbValid.Append(";");
ctl.Attributes.Add("onclick", sbValid.ToString());
}
See this asp.net thread for more info.
Update: the above code would be used to add the OnClientClick handler in code behind. You could also write the javascript in your aspx markup like so:
<script type="text/javascript">
function disableButton(button)
{
// if there are client validators on the page
if (typeof(Page_ClientValidate) == 'function')
{
// if validation failed return false
// this will cancel the click event
if (Page_ClientValidate() == false)
{
return false;
}
}
// change the button text (does not apply to an ImageButton)
//button.value = "Please wait ...";
// disable the button
button.disabled = true;
// fire postback
__doPostBack(button.id, '');
}
</script>
<asp:ImageButton runat="server" ID="VerifyStepContinue" ImageUrl="button.png"
ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="methodName"
OnClientClick="return disableButton(this);" />
I have solved this by setting a hidden field on the client click before hitting the server.
Then in the server I check the hidden field and if the value is for example something 'FALSE' that might mean I can or cannot of the action.
Similar to Silky's client-side response, I usually make two buttons that look alike except that the second button is disabled and hidden. OnClientClick of the normal button swaps the display styles of the two buttons so that the normal button is hidden and the disabled button is shown.
The double-click feature is a server-side implementation to prevent processing that same request which can be implemented on the client side through JavaScript. The main purpose of the feature is to prevent processing the same request twice. The server-side implementation does this by identifying the repeated request; however, the ideal solution is to prevent this from occurring on the client side.
In the HTML content sent to the client that allows them to submit requests, a small validation JavaScript can be used to check whether the request has already been submitted and if so, prevent the online shopper from submitting the request again. This JavaScript validation function will check the global flag to see if the request has been submitted and, if so; does not resubmit the request. If the double-click feature is disabled on the server, it is highly recommended that the JSP and HTML pages implement this JavaScript prevention.
The following example prevents the form from being submitted more then once by using the onSubmit() action of the form object:
...
<script>
var requestSubmitted = false;
function submitRequest() {
if (!requestSubmitted ) {
requestSubmitted = true;
return true;
}
return false;
}
</script>
...
<FORM method="POST" action="Logon" onSubmit="javascript:submitRequest()">
......
</FORM>
for those who just want to do a quick fix , just hide it and show another button that has no events
<asp:Button ID="RedeemSubmitButton" runat="server" Text="Submit to Redeem" OnClick="RedeemSubmitButton_Click" OnClientClick="hideit();" />
<asp:Button ID="RedeemSubmitButtonDisabled" style="display:none;" runat="server" Text="please wait" OnClientClick="javascript:alert('please wait, processing');" />
<script>
function hideit() {
var btn = $get('<%= this.RedeemSubmitButton.ClientID %>');
var btn2 = $get('<%= this.RedeemSubmitButtonDisabled.ClientID %>');
if (btn != null)
{
btn.style.display = 'none';
btn2.style.display = 'block'
}
}
</script>

Categories