I want prevent the client leave the page in my asp.net application
whithout saving ,the folowing code get option to leave the page without saving by click 'Ok'
in the confirm.
override confirm function not work in my browser(ie8)
<script type="text/javascript">
IsSaved = false;
window.onbeforeunload = function (e) {
return IsSaved ; }
</script>
where client save the data:
IsSaved = true;
EDIT:
I want to disable click on 'ok' button too.
Thanks.
You can’t override the confirmation function, because it’s a confirmation function. If a browser wouldn’t let the user close a page just because the page didn’t want to be closed, that would be a horrible security flaw.
Confirm like everyone else. And auto-save too.
window.onbeforeunload = function() {
return !isSaved && "You have unsaved (stuff). Are you sure you want to quit?";
};
I created a library I could include in all my web sites easily, so that this functionality would be easily accessible.
Put this class in a new C# class library project, so you can reference it from your other projects (web sites).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyNameSpace.ConfirmLeavePageScript
{
[DefaultProperty("TextToDisplay")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ConfirmLeavePageScript : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("Are you sure you want to leave this page?")]
[Localizable(true)]
public string TextToDisplay
{
get
{
String s = (String)ViewState["TextToDisplay"];
return ((s == null) ? "Are you sure you want to leave this page?" : s);
}
set
{
ViewState["TextToDisplay"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
string script = #"
<script type='text/javascript'>
var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = '" + TextToDisplay + #"';
if(typeof ConfirmLeavePageMessage != 'undefined') //give client side the opportunity to overwrite the message instead of using message from ViewState.
{
message=ConfirmLeavePageMessage;
}
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
function EnableConfirmOnPageExit()
{
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
}
function DisableConfirmOnPageExit()
{
// Turn it off - remove the function entirely
window.onbeforeunload = null;
}
</script>
";
output.Write(script);
}
}
}
You can register the tag prefix in your web site projects by putting this in your web.config. Make sure your website adds the C# class library project as a reference (put them in the same solution).
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="tna" assembly="ConfirmLeavePage" namespace="MyNameSpace.ConfirmLeavePageScript" />
</controls>
</pages>
</system.web>
</configuration>
Then, put the control in the head of your content pages.
<head>
<tna:ConfirmLeavePageScript runat="server" TextToDisplay="Are you sure you want to leave without saving?" />
</head>
In your JavaScript functions that detect if changes have been made, call this function:
EnableConfirmOnPageExit();
You can also do the following (which I think are self explanatory):
<script type="text/javascript>
ConfirmLeavePageMessage="new message"; //set a custom message from JavaScript for the confirmation window
DisableConfirmOnPageExit(); //Disables the confirmation window (user can leave page without seeing the confirmation window)
</script>
Related
I'm new to Javascript. I want to add an icon to all my project's web pages. This icon changes accordingly to whoever logs in in my page. What i'm trying now is, in master page load (when i have all of its data in codebehind, including his chosen icon), i introduced a js function to change icon:
(function icon(image) {
var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.hre = image;
document.getElementsByTagName('head')[0].appendChild(link);
})();
(adapted from here: Changing website favicon dynamically)
im trying to call this function with Page.ClientScript.RegisterStartupScript() method:
(protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//...
UserModel usuario = (UserModel)Session["usuario"];
//...
Page.ClientScript.RegisterStartupScript(this.GetType(), "icone", $"icone({(Bitmap)new ImageConverter().ConvertFrom(usuario.imagem)});", true);
}
}
The method is simply not executing(its not returning error either, it just "jump it"), and i sincerely have no idea why.
OOOOR, there may be a better way to do it, but i just cant figure it.
For the record, i DONT have the icons/images on a folder. I MUST get them form the database.
(I will later add validation for when user has no image in database. Assume for now it will never be null).
A few things need to be edited:
First, think you got the parameters for RegisterStartupScript not set as required. The 3rd value should be the javascript code to run. You can add the entire script as a variable (as indicated here: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.clientscriptmanager.registerstartupscript?view=netframework-4.7.2), or you can add your function in <script>...</script> tags to the HTML page, and then just call the function from within RegisterStartupScript (as the 3rd parameter value)
Secondly, there's a typo in your JavaScript function:
link.hre = image; should be link.href = image;
Thirdly, (this part might require some work) the image has to be a URL (string) to the actual image (Not the binary Bitmap)... you might first have to save the image to the web server as a .jpg or .png and use its URL to there, or you have to convert the image to Base64 and add the image via Data URLs https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Finally, you modified the JavaScript from the original example (you mentioned) In this case, you want to send the image URL as a parameter to the function icon However, the icon function is encapsulated. So the function is basically in a Private scope. Remove the encapsulation around the function if needed to be called from another function on the page... hope this make sense.
Instead of using Javascript, you could simply link your shortcut-icon to a handler, that immediately returns the image. (The following code is not tested, it's there to describe the basic process!)
In your page:
<link rel="shortcut icon" type="image/x-icon" href="/userimage.ashx">
userimage.ashx:
<%# WebHandler Language="C#" Class="UserImageHandler" %>
userimage.ashx.cs:
using System;
using System.Web;
public class UserImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "image/png"; // or image/jpg, image/bmp, ...
var image = FetchImageFromDatabase(context.User.Identity.Name); // your logic for fetching the image from the database
// You could also return a default image here, if the user has not selected one.
context.Response.Write(image); // Write the binary data to the response stream.
}
public bool IsReusable {
get {
return false;
}
}
}
I'm limiting the amount of certain pop up windows with a static counter in the back-end of my web form application (C#). I only want to have 1 window open at a time. The back-end counter works fine, however when a user closes the child window I want to reset the counter in the back-end. For that I'm using AJAX with JS (can't use JQuery) and I'm calling that AJAX to make a POST in the back-end in an onUnload event.
I'm using IE 11.
Back-end method I want to call from my JavaScript.
public void DecreaseItem1()
{
int? inspID = convert.ToInt(Request.QueryString["inspid"]);
int? inpID_static = InspectionList.GetWindowInspID();
string path = HttpContext.Current.Request.Url.AbsolutePath;
if (path.Contains("ReadOnlyInspection"))
{
if (inspID != inpID_static)
{
InspectionList.DecreaseCounter();
}
else
{
InspectionList.DecreaseCounter();
InspectionList.SetGetWindowInspID(null);
}
}
From my front-end I'm calling onUnload the DecreaseItem() JavaScript function.
Body tag
<body onUnload="DecreaseItem()" >
JavaScript function:
<script type="text/javascript">
function DecreaseItem() {
var win_loc = "ReadOnlyInspection.aspx/DecreaseItem1";
var xhttp = new XMLHttpRequest();
xhttp.open("POST", win_loc, true);
xhttp.send();
}
</script>
[problem] Counter never gets decreased. Any help or suggestion is greatly appreciated.
I am noob to ASP.net.
I was trying to add a confirmation popup to webpage.
I used the following code :
(which is a variant from this one: http://www.codeproject.com/Articles/8173/A-Simple-ASP-NET-Server-Control-Message-Box-Confir )
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Text;
namespace BunnyBear
{
[DefaultProperty("Text"),
ToolboxData("<{0}:msgBox runat=server></{0}:msgBox>")]
public class msgBox : System.Web.UI.WebControls.WebControl
{
//private string msg;
private string content;
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public void confirm2(string msg)
{
string sMsg = msg.Replace("\n", "\\n");
sMsg = msg.Replace("\"", "'");
StringBuilder sb = new StringBuilder();
sb.Append(#"<script language='javascript'>");
sb.Append(#" if(confirm( """ + sMsg + #""" ))");
sb.Append(#" { }");
sb.Append(#" else { ");
sb.Append( "document.forms[0].submit(); }");
sb.Append(#"</script>");
content = sb.ToString();
}
protected override void Render(HtmlTextWriter output)
{
output.Write(this.content);
}
}
}
I try it from a test class as follows :
//event triggered when clicking a button
protected void Button2_Click(object sender, EventArgs e)
{
msgBox1.confirm2("are you sure?");
MoreCode();
}
I was expecting that when I click on the button, the confirmation popup pops and asks if I want to confirm:
if I click "no" : postback occurs so MoreCode() is not executed
If I click "yes" : no javascript code is executed, so the execution goes on and MoreCode() is executed.
This is not what happens.
When I click the button with the step by step debugger, I can see that :
it executes msgBox1.confirm2("are you sure?");
it then executes MoreCode()
and afterwards the popup pops
Could you pls explain me why this is executed in this order?
Thanks in advance.
MoreCode() is running on the server side, whereas the popup is on the client side. They are independent operations. If MoreCode must run after the button click, then you need to have a callback in your JavaScript, appending it after
sb.Append(#" if(confirm( """ + sMsg + #""" ))");
The callback would bind to a server call, and that server call would execute MoreCode.
Since you are not using any AJAX, the order of operations is clear: all server-side code is run, then HTML is returned to the browser where the browser executes any necessary client-side code. Here is what happens, in order, starting from when your Button2 is clicked:
Button2_Click server event is called. This event does everything it is asked to do: create a string that will be injected to the resulting HTML page, and then run MoreCode(). Control has not yet been returned to the browser--all this processing is handled on the server-side.
HTML for the resulting page is rendered, along with the string you injected, which includes the JavaScript you have written.
HTML is transferred to the browser and the HTML is executed. Your script triggers a JavaScript prompt, which is then displayed to the user using the text that was specified server-side.
I have a script to create an ActiveX component that works fine when run from the command line but reports:
SCRIPT429: Automation server can't create object
when run from JavaScript in a html page. I know the web page JavaScript works OK when I try and create a different ActiveX component like Excel.Application so I think it is something about the particular ActiveX component I am trying to create.
How can I debug this? Id there some flag I can check to see if the ActiveX component will not allow itself to be created in a web page?
The web page JavaScript looks like this:
<script language="javascript" >
function MakeOne()
{
var obj = new ActiveXObject('ECRUtilATL.Transaction');
obj.Amount1In = "12.53";
var result = "";
if (obj == null) {
result = 'null';
}
else {
result = 'not null';
}
alert(result);
}
</script>
I m using some serverside validation and if any problem comes I m showing a pop up message using javascript using
page.ClientScript.RegisterClientScriptBlock
but when my message is displayed the background of the window turns gray.
can any one help me to get rid of this gray window
public static class Alert
{
/// <summary>
/// Shows a client-side JavaScript alert in the browser.
/// </summary>
/// <param name="message">The message to appear in the alert.</param>
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;
// Checks if the handler is a Page and that the script isn't allready on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}
I am using this Function
Since you are using the Javascript alert() function, you have absolutely no control over how the browser handles it. Each browser looks slightly different. However, you can expect that it will be a modal popup with your content, and a single "Ok" button. Beyond that, you have no control.
If you want something different, you'll have to use more complex javascript; perhaps using a jQuery plugin to display your message exactly how you want, or overriding the alert() function.