How to open new browser window on button click event? - c#

How to open new browser window on button click event in C# ASP.NET?
Please share any example.
I am doing following code. Please let me know where I am going wrong.
btn_Click()
{
if(condition==true)
{
this.Page.ClientScript.RegisterStartupScript(
this.GetType(),
"page_index_script2",
"openNewWindow();",
true
);
}
}
And the JavaScript function is
function openNewWindow()
{
alert('HI');
window.open('http://www.stackoverflow.com');
}
When I run the code from javascript function Alert works but new window is not getting opened.

You can use some code like this, you can adjust a height and width as per your need
protected void button_Click(object sender, EventArgs e)
{
// open a pop up window at the center of the page.
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
}

It can be done all on the client-side using the OnClientClick[MSDN] event handler and window.open[MDN]:
<asp:Button
runat="server"
OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
Open a new window!
</asp:Button>

Response.Write('... javascript that opens a window...')
http://www.aspspider.com/qa/Question2714.aspx

Or write to the response stream:
Response.Write("<script>");
Response.Write("window.open('page.html','_blank')");
Response.Write("</script>");

Related

How to open page in new tab using the response. redirect at asp.net

I want to open a new tab or a new page by using Response.Redirect in a button click handler. I'm using a query string to pass some values. How can I open he page in a new tab?
protected void btnSave_Click(object sender, EventArgs e)
{
...//some code to insert records
Response.Redirect("NewQuote.aspx?val=" + this.txtQuotationNo.Text);//displaying gridview in other page to print what needed
}
Try this. This works sure for me...
protected void btnSave_Click(object sender, EventArgs e)
{
...//some code to insert records
Response.Write("<script>window.open ('NewQuote.aspx?val=" + txtQuotationNo.Text+"','_blank');</script>");
}
Simple solution is here.
Edit your html button element and add attribute OnClientClick="target ='_blank';".
<asp:Button ID="myButton" runat="server" CssClass="btn1"
OnClick="btnSave_Click" OnClientClick="target ='_blank';" />
Then in btnSave_Click
protected void btnSave_Click(object sender, EventArgs e) {
Response.Redirect(url);
}
You can change your design element as below : OnClientClick
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick ="document.forms[0].target = '_blank';" />
Javascript code :
Response.Write("<script>");
Response.Write("window.open('NewQuote.aspx' ,'_blank')");
Response.Write("</script>");
I encountered this same problem today.
Response.write didn't work for me, to solve it I used instead System.Web.UI.ScriptManager.RegisterClientScriptBlock.
This is how your btnSave click event should be:
protected void btnSave_Click(object sender, EventArgs e)
{
...//some code to insert records
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "openModal", "window.open('NewQuote.aspx?val= "+ this.txtQuotationNo.Text+"' ,'_blank');", true);
}
NOTE: I'm using ScriptManager.RegisterClientScriptBlock because the button is inside an UpdatePanel, if that's not your case you should try:
protected void btnSave_Click(object sender, EventArgs e)
{
...//some code to insert records
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "openModal", "window.open('NewQuote.aspx?val= " + this.txtQuotationNo.Text + "' ,'_blank');", true);
}
if you are using http
then use below code
Response.Write("<script>window.open ('URL','_blank');</script>");
this code cannot be used for https
for https do below
javascript in page
function shwwindow(myurl) {
window.open(myurl, '_blank');
}
in c# code behind
string URL = ResolveClientUrl("~") + "**internal page path**";
ScriptManager.RegisterStartupScript(this, this.GetType(), "show window",
"shwwindow('"+URL+"');", true);
this code cannot bybass the browser popup blocker. user must allow it to run.
for ie it opens in new window or new tab up to ie version
in firefox and chrome it opens new tab
enjoy it!!
A redirect is always in the same page as where you came from, you can't open a new window from a redirect call.
I would suggest to inject some javascript code in the client to open the new page on reload, or change to a control that can open to a new page, like a LinkButton with the right Target attribute.
You can use ScriptManager to do the needed:
private void Redirect_New_Tab(string url_To_Open)
{
string modified_URL = "window.open('" + url_To_Open + "', '_blank');";
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", modified_URL , true);
}
Worked for me when I left the Double Quotes off of target ='_blank';
Response.write didn't work for me, so I used instead System.Web.UI.ScriptManager.RegisterClientScriptBlock.
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "openModal", "window.open('NewQuote.aspx?val= "+ this.txtQuotationNo.Text+"' ,'_blank');", true);
I spent quite some time on this, and while it does work to set the target on the form to _blank it will mean that every other control on that page will attempt to open in a new window afterwards. And you can't manipulate the form back server side, since the response will never reach the orginal tab.
So I made it work with a combination of setting the target to _blank when the button is clicked, and then shortly after reset the target back.
I put in this Javascript function on the page:
<script type="text/javascript">
function openInNewTab() {
document.forms[0].target = "_blank";
setTimeout(function () {
document.forms[0].removeAttribute('target'); // After 500 ms revert back to normal mode so all other controls are not affected.
}, 500);
}
And on the control that needs to open in a new tab just add:
OnClientClick="openInNewTab();"

how to close current webform after display messagebox

I use the code below to open a message box:
protected void btnUpdate_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Messagebox", "alert('Record Updated successfully.Note: This tab is now getting close');", true);
}
How to close the current page after a click on the OK button of this message box?
in web forms you can't close the page, what you will have to do is redirect the page to a different page, and if you add the redirect after the alert it should happen when the alert closes
if you don't know how to redirect a page then this may help
aspx page to redirect to a new page
however webforms is something i'm still learning myself
Open the current page as popup using window.open() then write a Javascript function in the page such as
<script>
function confirmAndClose()
{
var conf = confirm("Confirm to close");
if (conf == true) {
window.close();
}
}
</script>
then change you server side code to
ScriptManager.RegisterClientScriptBlock(this, "script","confirmAndClose()");
Try this,
string message = "alert('Your Approval Has Been Saved Success');self.close();";
ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true);

How to refresh the page? (Click button close RadWindow)

I have 2 pages (Home and Сategory)
Load page Home on there's button. Click button run panel RadWindow (NavigateUrl: Сategory).
protected void ShowWindow()
{
string script = "function f(){$find(\"" + RadWindow_editor.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
}
protected void RadButtonEdit_Click(object sender, EventArgs e)
{
ShowWindow();
}
Load RadWindow NavigateUrl - Сategory on there's button. Click button close RadWindow.
protected void RadButtonEdit_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "Close();", true);
}
function GetRadWindow() {
var oWindow = null;
if (window.radWindow)
oWindow = window.radWindow;
else if (window.frameElement.radWindow)
oWindow = window.frameElement.radWindow;
return oWindow;
}
function Close() {
var oWindow = GetRadWindow();
oWindow.argument = null;
oWindow.close();
return false;
}
How to refresh the page Home? (Click button close RadWindow)
Thank you!
Here's how: http://www.telerik.com/community/forums/aspnet-ajax/window/how-to-refresh-the-page-click-button-close-radwindow.aspx#2894238.
If your page does not refresh, then the problem is in the page. Having a has in the URL can cause this problem. Make sure you change the URL so you have a fresh GET request.
There are client-side events like OnClientBeforeClose and OnClientClose.
http://demos.telerik.com/aspnet-ajax/window/examples/clientsideevents/defaultcs.aspx
and check this link, it gives you an idea.
How to close the radwindow on serverside and refresh the parent page
You should also look at using a RadAjaxManager in the parent page to send the window events to the parent as shown in the the following demo: Grid and Window. It focuses on refreshing a grid, not a page in your instance, but the concept of sending events to the parent page remains the same.

Close the Page on a Button click ASP.NET C#

I have a "save & close" button where I need to close my page after saving the data. I have tried many ways, but none of them worked.
Code-behind:
protected void btnSaveClose_Click(object sender, EventArgs e)
{
Save();
ClientScript.RegisterClientScriptBlock(Page.GetType(), "script", "window.close();", true);
}
I need help closing the window.
The MDN documentation on the close method explains some of the limitations:
This method can only be called on windows that were opened by a script using the Window.open() method. If the window was not opened by a script, an error similar to this one appears in the console: Scripts may not close windows that were not opened by script.
In other words, this method simply won't work unless the window was opened with the Window.open() method.
You don't "close windows" in a Web application. Simply display a friendly message to the user as confirmation or a friendly error message, whichever the case may be. You can easily do this using three panels:
<asp:Panel id="formPanel" runat="server">
<!-- Your form controls go here -->
</asp:Panel>
<asp:Panel id="confirmPanel" runat="server">
<!-- Confirmation message -->
</asp:Panel>
<asp:Panel id="errorPanel" runat="server">
<!-- Error message -->
</asp:Panel>
Just toggle the visible property of these panels at the appropriate points in your code-behind.
string display = "Your dispaly";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);//this will dispaly the alert box
ScriptManager.RegisterStartupScript(this, this.GetType(), "Close_Window", "self.close();", true);//this will close the page on button click
This Worked for me
Thanks to all
This working for me, so I will recommend it:
protected void Page_Load(object sender, EventArgs e)
{
this.CloseBtn.Attributes.Add("OnClick", "self.close()");
}
protected void CloseBtn_Click(object sender, EventArgs e)
{
Response.Write("<script language='javascript'> { self.close() }</script>");
}
Thank you all. Here is the solution which fixed it.
protected void Page_PreRender(object sender, EventArgs e)
{
if (ViewState["closewindow"] != null)
closewindow = (bool)ViewState["closewindow"];
if (closewindow)
{
closewindow = false;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Close_Window", "self.close();", true);
//System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Close_Window", "self.close();", true);
}
}

Popup window after submit

Just to ask a straight question, when I complete adding some data in my page and click submit button, how can I make a popup window saying that the information has been successfully added in database instead of make a new page? Is there any ways that I can do? Any website to be referred? Thanks
You may create a re-usable function for it .
public void Show(string msg)
{
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
ScriptManager.RegisterStartupScript(page, page.GetType(), "msg", "alert('" + msg + "');", true);
}
}
and in submit button call like this.
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Your Code for submit
Show("Save Success");
}
You have to just put below code:
Response.Write("<script>alert('information has been successfully added')
</script>");
You could set a label text with your message and make it visible when you want to show the message.
lblMessage.Text = "Data updated successfully";
lblMessage.Visible = true;
To make it prominent, you could use jquery dialogs, and style it appropriately with CSS.
ScriptManager.RegisterStartupScript(this, this.GetType(), "Notification", "alert('Done');", true);
Using ASP.NET you would be still undergoing a full page life cycle if you are submitting your form with a regular submit behavior. This means that the page would first need to reload and then to fire your alert. If you want the page to not reload but instead just show a result alert, you would need to perform your action with AJAX, POSTing the form to a service method which updates the database you have. This would not reload your page and would just show an alert which your ajax call is complete. jQuery $.post()
On the click of your button after checking for valid data you can do something like this
ClientScriptManager script = Page.ClientScript
if (!script.IsStartupScriptRegistered(GetType(), "Show Popup"))
{
script.RegisterStartupScript(GetType(), "Show Popup", "ShowPopup();", true);
}
You can call javascript function from code behind using ClientScriptManager.RegisterStartupScript Method
Here is you Popup
HTML:
<div id="Popup"></div>
CSS:
#Popup
{
height:200px;
width:300px;
position:fixed;
z-index:102;
left:50%;
top:50%;
margin-top:-130px;
margin-left:-180px;
font-weight:bold;
font-size:10pt;
padding:20px;
background-color:#fff;
border:10px solid #9cc3f7;
border-radius:20px;
-webkit-border-radius:20px;
-moz-border-radius:20px;
text-align:center;
display:none;
}​
Jquery function:
function ShowPopup()
{
$('#Popup').show("slow");
}​
See Sample
//Global Declaration
public static void Message(String message, Control cntrl)
{
ScriptManager.RegisterStartupScript(cntrl, cntrl.GetType(), "alert", "alert('" + message + "');", true);
}
//Call any where, where you want to display message
Message("Any message here", this);

Categories