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);
}
}
Related
I am developing an application by using ASP.Net WebForm. Once user click a button, application will navigate to a new page and prompt out a dialog box "Welcome to JackiesGame"
However, I able to navigate to new page but the alert dialog box does not display.
The following is my sample code
void cmdCancel_Click(object sender, EventArgs e)
{
HttpContext.Current.Response.Redirect(Globals.NavigateURL(TabId), true);
Page page2 = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterStartupScript(page2, page2.GetType(), "alertMessage", "alert('Insert Successfully')", true);
}
Add the following in page 2. On the page load it will register only for the first time the page loads the script.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
var reg = Request["Welcome"]
if(reg != null && reg.ToString() == "yes"){
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertMessage", "alert('Insert Successfully')", true);
}
}
}
All code after the redirect is getting ignored since it has to redirect to a new page. So the code never gets triggered.
EDIT
Added a example of how it can look further
void cmdCancel_Click(object sender, EventArgs e)
{
string myUrl = Globals.NavigateURL(TabId)+"?Welcome=yes";
HttpContext.Current.Response.Redirect(myUrl, true);
}
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();"
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);
Ok, I want to allow user to be able to use the page only when browser is Chrome or IE8-9.
I doing so from code behind as you can see. And also trying to set viability of main div to none.
protected void Page_Load(object sender, EventArgs e)
{
System.Web.HttpBrowserCapabilities browser = Request.Browser;
if (browser.Type.ToString().ToLower().StartsWith("ie"))
{
if (Convert.ToDecimal(browser.Version) < 8 || Convert.ToDecimal(browser.Version) > 9)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "pop", "<script>alert('Your browser is not supported. Please use Chrome or IE7,IE8,IE9');</script>", false);
pagecontainer.Attributes["style"] = "visible:none";
return;
}
}
else if (!browser.Type.ToString().ToLower().StartsWith("chrome"))
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "pop", "<script>alert('Your browser is not supported. Please use Chrome or IE7,IE8,IE9');}</script>", false);
pagecontainer.Attributes["style"] = "visible:none";
return;
}
//blah blah
}
<div id="pagecontainer" runat="server" >Page Content Goes Here</div>
But it does not seem to be hiding the div.
I know I can always redirect user to a warning page or something but lets say I do not want to do so. What are my alternatives?
remove this line:
pagecontainer.Attributes["style"] = "visible:none";
and use this one instead:
pagecontainer.Attributes.Add("style", "display:none;");
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>");