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;");
Related
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);
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);
}
}
I am working in C#.Net. I want to kill the session values when the browser is closed. (i.e) In my application, i want to display online visitors count. If the user clicks logout button means, it works fine. rather than if he close the browser, the session value not cleared.
if the browser close is done, the session value should be killed....
My Global.ascx code...
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application["OnlineUsers"] = 0;
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
Application.UnLock();
}
My Home.aspx code...
Visitors online: <%= Application["OnlineUsers"].ToString() %>
If i run my application in IE, the online count will be 1. If i runs in Firefox, the online count should be incresed to 2. If i close the Firefox browser, the count in IE should be changed to 1.
This is my Requirement....
The Http protocol is a connectionless one, so unless you are planning to use websockets, the only two ways to kill the user session should be by a direct request by the user (i.e. pressing a logout link), or a session timeout.
You should not rely on the browser to kill the session. The user can forget to close the browser, or he may have javascript disabled. Instead, provide means to the user to close the session and set your session timeout to a reasonable value adjusted to your users activity.
if (!Session.IsNewSession && Request.UrlReferrer == null)
{
}
if we type or paste url, this code will redirect to login page
You could trigger javascript, like this:
<SCRIPT language="JavaScript">
<!--
function loadOut()
{
window.location="http://www.yoursite.com/loadout.php?sid=235346317";
}
//-->
</SCRIPT>
<body onBeforeUnload="loadOut()">
Your javascript could perform an AJAX call, or whatever.
This will also work, I think, when the user leaves your site.
Is this what you were searching for?
How about this:
<body onunload="doUnload()">
Then the javascript, would be something like:
function doUnload()
{
$.post("unset_session.php", { action: "unset" },
function(data) {
// Callback if wanted
});
}
Then in your php, just unset the session data, or destroy the session
<?php
if ($_POST['action'] == 'unset')
{
// Unset or Destroy the Session
session_destroy();
}
?>
I did this in my .net app for IE, when user click browser right up corner X button, I want to force user logout. Hope that helps.
In master page:
<script type="text/javascript">
window.onbeforeunload = function (e) {
//alert("Killing the session on the server!!");
if ((window.event.clientX < 0) || (window.event.clientY < 0)) {
document.getElementById('<%= FORCE_LOGOUT_BTN.ClientID %>').click();
}
}
</script>
In .net site.master page:
<asp:Button ID="FORCE_LOGOUT_BTN" runat="server" CssClass="noShow"OnClick="ForceLogOut" Width="10px" />
Have to use CssClass, set Visible=false not working, since object will become null. Css noShow is: visibility:hidden;
In site.master.cs
public void ForceLogOut(object sender, EventArgs e)
{
FormsAuthentication.SignOut(); // since I use Form authentication
Session.Abandon();
}
I have a problem: when i call a Response.Redirect() from the MasterPage it doesn't work.
Well, debugging i can see that until the Pre_Render() method the target page is loaded, but then is rendered the previous page.
Here's some code to better explain:
(from MasterPageMain.master.cs)
protected void Page_Init(object sender, EventArgs e)
{
string m_QueryStringValue = Request.QueryString.Get("action");
if ((!string.IsNullOrEmpty(m_QueryStringValue)) && (m_QueryStringValue.ToLower() == "send"))
{
if (Session["to"] != null && Session["to"] is List<string>) this.SendPageByMail();
else
{
Session.Add("AddressToSend", Request.RawUrl);
Response.Redirect("~/chooseRecipients.aspx");
}
}
}
I have a javascript that adds the querystring adding "action=send" when i click on the Send button.
If i am on page "~/somethingInterestingToSend()" -for example- i want to get on the recipient selection page, but when i click the Send button i see always the same page.
What coul be the mistake?
If you want to redirect not logged in users to a login-page you should check the Request.RawUrl() like this:
string strURL=Request.RawUrl.ToUpper();
if (!strURL.Contains("LOGIN.ASPX") && !strURL.Contains("LOGOUT.ASPX")
&& !strURL.Contains("ERROR.ASPX") && !strURL.Contains("UNDERCONSTRUCTION.ASPX"))
{
Response.Redirect("~/Login.aspx", false);
}
All other sites will be redirected.
I am not sure I fully understand your description of the problem, but here are a few things to consider:
You mention a send button. If this is an , clicking it fires a javascript postback to the server. This postback is to the original URL. I'm not sure what you are modifying with Javascript, but I don't think it would change the postback URL (and querystring).
If you need to perform logic to redirect you might want to execute in the button click event on the server.
If you don't need to execute any logic on the server, you could to the redirect with javascript:
window.location = "chooseRecipients.aspx";
Can't test this theory (running from memory at the moment), but give this a shot:
(sorry, cleaned up the code a bit as well)
protected void Page_Init(object sender, EventArgs e)
{
string m_QueryStringValue = Request.QueryString.Get("action") ?? "";
if (m_QueryStringValue.ToLower() == "send")
{
if ( (Session["to"] as List<string>) != null)
{
this.SendPageByMail();
}
else
{
Session.Add("AddressToSend", Request.RawUrl);
Response.Redirect("~/chooseRecipients.aspx", false);
HttpContext.Current.ApplicationInstance.CompleteRequest()
}
}
}
I don't know if its the root of your problem but I'd change 2 things. I'd change your code to:
Response.Redirect("~/chooseRecipients.aspx", false);
and move the logic to PageLoad