I have a save button which when clicked should make some changes in the database.
if (bFound== false)
{
// Giving the warning message
// If user presses cancel then abort
// Prepare the list of dbId needs to be deleted
deletedBSIds.Add(dbId);
}
Here if the bFound field is true it should not execute the above statement, but if it is false it should go in the condition and then ask if the user want to save changes "yes" or "no".
If the user says yes it should go to the command "deletedBSIds.Add(dbId);" and keep executing further but if the user presses No it should basically abort and do nothing at all.
Is there a way to do this?
Any help would be appreciated.
This is a server side event. so i think cannot add a click event in my button/..
Here the message box only pops up if the bFoung field is false. or else it will not pop up at all.
Please correct me if u feel i am wrong..
thanks
You'll want to add the following to the button:
button.OnClientClick = "return ConfirmThis();";
You'll then need to add the ConfirmThis function to the Page:
Page.ClientScript.RegisterScriptBlock(GetType(), "ConfirmThis",
#"function ConfirmThis() {
if(condition) { //where condition checks the bfound element.
return confirm(""Are you sure you want to delete this?"");
}
return true;
}");
Doing this approach you're going to want to try and be able to test the bfound condition on the client side in the javascript. If the bfound value is stored in a textbox or HiddenField you should use the document.getElementById function. If the bfound value is known when you are creating the page, you can inject it into the ConfirmThis function directly, of pass it into the ConfirmThis function as a parameter.
Edit in response to your edit:
You have two options when trying to elicit a confirm from the user:
Using client side logic that is already sent to the browser to perform the confirm. This is the example that I have given above.
The "Other" option is to send the page back with a modal dialog, or using the confirm box. You will then get the user's confirmation back in a completely new postback to the server. So you'll need to rethink your logic to be able to temporarily store the information from the first post back and wait for the second post back to finalize the desired action.
Of the two examples, the first option is cleaner and requires no temporary memory and saves the user an additional postback.
Because both options are going to require you to rework the logic asking for the confirm, if at all possible I would try to convert the logic required for the condition to show the confirm dialog to be able to be performed on the client's computer with javascript.
Is there any way you can precalculate the bfound variable, or at the least, send enough information for it to be calculated on the client?
If you still feel like using option 2 after all of my pleading:
use the following code (based on http://www.dotnetspider.com/resources/1521-How-call-Postback-from-Javascript.aspx:
if(bfound)
{
//save all the information you need in temporary information
ViewState["InformationINeedToFinishAfterPostback"] = ImportantInformation;
Page.ClientScript.RegisterScriptBlock(GetType(), "postbackmethod", Page.ClientScript.GetPostBackEventReference(this, "MyCustomArgument"));
Page.ClientScript.RegisterStartupScript(GetType(), "startupconfirm",
#"if(confirm(""are you sure?"") {
__doPostBack('__Page', 'MyCustomArgument');
}");
}
Now to handle the postback add the following code to your page_load:
if(Request("__EVENTARGUMENT") == "MyCustomArgument")
{
ImportantInformation = (CastToAppropriateType)ViewState["InformationINeedToFinishAfterPostback"];
//finalize the desired action here.
}
But... I would still recommend the first option. But now you have the code you will need for both options. Also, I didn't test this code, so you're bound to encounter syntactic problems, but it gets you on the right track.
I'm not all that sure what bfound is supposed to represent, but you can't execute 1/2 way through some server code and then go back to the client- ASP.NET does not work that way.
Typically you will do the confirmation with some client side JavaScript. Google ASP.NET Yes/no confirm to find lots of different ways to do this...
Once you've done this you can then conditionally execute the server side code.
You could use the Javascript confirm() function to display a dialog box to the user with 'OK' and 'Cancel' prompts. You could then store the user's choice in a hidden field and trigger a postback. This article explains how to render Javascript code to the client using ASP.NET.
Since you are using ASP.NET you can add an attribute to your button:
btnDelete.Attributes.Add("onclick", "return confirm('Are you sure?');");
Where btnDelete is your Button.
Related
This question already has answers here:
Javascript confirm box in C# code behind
(3 answers)
Closed 9 years ago.
else if (Result == 1)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", "return confirm('Are you sure you want to delete? This action cannot be undone.')", true);
FSI.DeleteINsertData(ID.ToString(), No.ToString());
}
I have a js confirmation on code behind. I want to continue process when the user click "yes", otherway , user click "no", do nothing. it is in else if statement.Thanks for your answers.
Use:
Response.Write("<script>confirm('Are you sure you want to delete? This action cannot be undone.');</script>");
Might Work!
Your question implies that what you want to do is pause the server-side code (before you delete anything) while you wait for some client-side code to execute (throwing up the confirmation box to make sure the user does want to perform the delete). This simply isn't the way things work.
All the ScriptManager.RegisterClientScriptBlock(...) call does is tell the server that it should include that script when it sends the response to the client. It doesn't then pause and send the script; instead it just carries on, executing the deletion and then the page and script gets sent to the client. You can't change that behaviour - it's a fundamental part of how server-side web programming works.
Your options really are to have the delete button/link that they clicked in the first place throw up the confirmation box before you even go to the server (cancelling the form-submission or link-click if they've changed their minds), or alternatively to have the server reply to that submission/click with a confirmation page that requires them to click another button, which then goes back to the server again to actually perform the delete.
I think you can make merge between server side and Client side.
You can add your script as code behind:
string scriptStr = "<script>var confirmation = confirm('something');
if(confirmation){document.getelementbyid('button').click();}
else{//something else}</script>";
RegisterStartupScript("ScriptFunction", scriptStr );
and then in your code behind handle the button click event.
This may works for you.
In my current project I've got a workflow in which I need to show two consecutive MessageBoxes to the user. The first one is more like a warning, that informs the user of the risk of the operation he tries do execute. I am using the ClientClickEvent of a link button to let the user confirm the operation:
<asp:LinkButton runat="server" id="lockorder"
CommandName='LockOrder'
OnClientClick="return confirm('Do you really want to lock this order?');" />
If the user confirms that he is sure to perform the operation, the application performs some validation from code behind. The result can be, that there are some unhandled tasks. This is valid, but the user should get informed about it, to have the possibility to finish those tasks. So I show a second confirmation dialog, but this time from code behind:
if (tasksOpen)
{
ScriptManager.RegisterClientScriptBlock(
this.Page,
typeof(Page),
"Onload",
"var confirmationResult = window.confirm('There are some open tasks left, which might get closed. Do you really want to lock this order?'); if (confirmationResult) __doPostBack('ConfirmLockOrder', confirmationResult);",
true);
return;
}
For better readability here is the JS-snippet that get's handed to the client:
var confirmationResult
= window.confirm('There are some open tasks left, which might get closed. Do you really want to lock this order?');
if (confirmationResult)
__doPostBack('ConfirmLockOrder', confirmationResult);
Back again in code behind I am receiving this command (e.g. inside the Page_Load event) and continue with the actual operations. All worked fine, but with some change I've done it stopped performing the postback.
I've took a look at the client script using FireBug. The __doPostBack-function (which is apparently auto-generated) tells me that WebForm_OnSubmit is not defined. I think it is not defined, because the confirmation dialog get's shown in the OnLoad-event and thus before the form is actually loaded. But why does the __doPostBack-function even need to check if this event performed, if it is not defined? Can I customize the __doPostBack-behaviour? Or should I choose another event? Or am I completely wrong here?
I hope somebody can point me into the right direction!
Based on the error (and some educated guesses), your JavaScript code that you are registering via ScriptManager is firing before the rest of the JavaScript code generated by ASP.NET is loaded. Hence, WebForm_OnLoad is undefined.
You need to make certain that the web page is completely loaded before your code executes. Change your code to the following:
window.onload=function(){
var confirmationResult = window.confirm('There are some open tasks left, '
+ 'which might get closed. Do you really want to lock this order?');
if (confirmationResult)
__doPostBack('ConfirmLockOrder', confirmationResult);
}
*I broke the confirm string into two, just for display purposes.
If you use jQuery, $(document).ready is preferred over window.onload.
I have a web page that contains a textbox and a submit button. When the user edits the text in the textbox and clicks another link (not the submit button) how do I display the 'Are you sure you want to navigate away from this page' popup message?
I have researched this on the net and found a few javascript examples. Is this the only way you can do this? If not, what is the best way to do it?
This is one of the multiple ways to achieve the same thing
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
got it from here open js
Only the unload() event will work on JS. You can't manage it on the server.
Check out the answer to this other question on SO, it is very similar to your question
How to show the "Are you sure you want to navigate away from this page?" when changes committed?
Simple solution
window.onbeforeunload = confirmExit;
function confirmExit() {
return "Are you sure you want to leave this page?";
}
4guysFromRolla.com - Prompting a user to Save when Leaving a Page
You cannot use the onbeforeunload window method as it gets triggered by multiple ways like back and forth browser navigation links, refreshing the page, closing of the page, clicking on the links.
What i feel you have to bind the link tag for which you want display the navigation away message and then use the function for the status message display
window.addEvent('domready',function(){
$$('a').addEvent('click', function(e) {
//leaving(); function u wrote for displaying message
});
});
function leaving(e) {
if(!e)
e = window.event;
// return code for the displaying message
}
If you want to do this in a way that guarantees it will work on almost all browsers, use the JQuery library. The following describes the unload event.
http://www.w3schools.com/jquery/event_unload.asp
It's exactly for purposes like yours.
Just to elaborate a little, you would have to download the jquery js library and reference it in your project/page, but you'll probably want to do that eventually anyway.
If you want to control this from the server side, you can dynamically emit the jquery call in the OnPreRender.
Look into Jquery's .beforeunload property. Here is an example:
$(window).bind('beforeunload', function(){ return 'Click OK to exit'; });
Please note, beforeunload canot prevent a page from unloading or redirect it to another page for obvious reasons; it would be too easy to abuse. Also if you just want to run a function before unloading, try the following:
$(window).unload(function(){ alert('Bye.'); });
Finally, don't forget to referrence jQuery in your head tag by using:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
The above gets you the latest version from the internet and saves you the trouble to download it, and of course you can do so optionally, but I am just trying to get your thing to work asap.
Oh, I also found an example for you. Click here to see a page that calls a function before it closes. Hope this helps bud.
I was able to get this to work with Andrei G's answer. I would add on that to get it to work in Chrome, add this to the end of his goodbye function:
return "";
I have to show a yes no popup messagebox for a function>
This is what i do for an alert popup>
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script>alert('File Updated');</script>");
This is what i want to do in the code behind:
if (ID != 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Confirm", "<script>confirm('are you sure?');</script>");
if (yes)
{
perform function
}
else
{
return;
}
}
The confirm is not working,,, any suggestions on how to do this
thanks
Edit Portion:
Navigate to a page
Add values to a textbox
Click "Save" Button to add value to database
Ask the user if he is sure he want to do it 'are you sure'?,, the confirm pop up
Now the above confirm box will only happen if the ID is != 0 or else there is no need for a popup.
if he says yes then add to database and show alert popup that values have been enterd in the DB.
if NO then just dont add to Db and just return.
so i get the confirm box like this.. but how can i get what is selected
string scriptString = "<script language='JavaScript'> ";
scriptString += "confirm ('Are you sure you want to Close this period.')";
scriptString += "</script>";
Response.Write(scriptString);
Is there a button you are clicking on to trigger the action? If so, you should add the client events to your web control like so:
<asp:ImageButton runat="server" ID="DeleteUrlImageButton" ImageUrl="~/Images/icon_remove.gif"
OnClick="DeleteUrlImageButton_Clicked"
OnClientClick="return confirm('Are you sure you want to delete?');" />
If the user selects yes, the postback happens as usual. If they select no, the even is cancelled and no postback occurs. This, IMO, is the way to handle it because it prevents any extra server activity if they select no.
Add a linkbutton.
In the OnClientClick add
javascript:return confirm('Are you sure')
This will not launch the postback if they click no. It will launch the postback if they click yes.
Then in then code behind (OnClick) of the button do your server side processing:
(Will only be executed if they click yes)
if (ID != 0)
{
Perform function
}
See the problem here is that, without posting back, you can't get the value of the confirm box. JavaScript is run client-side and until a postback occurs (either via ajax or the regular way), it can't "talk" to your C# file.
What you'll have to do is add a confirm box in JavaScript which, if Yes is clicked, will post back to your Asp.net page and run code either through Ajax or (example) form.submit().
It appears that what you're trying to do is (in a simplified scenario):
Have the user navigate to Page.aspx
Check the value of ID (lets assume
it's a querystring parameter)
If the value of ID is non-zero, prompt
the user to confirm
If they confirm do "something"
The mistake you're making is attempting to handle 2, 3 and 4 alltogether in the code-behind. The script that you emit (by calling RegisterStartupScript) doesn't get executed until the entire page has been rendered back to the user, at which point the code for steps 3 and 4 to check the value of ID and do something will already have been "skipped over"
What you need to do is decide how to separate the work between client-site and server-side as what you're attempting to do just won't work. Without knowing how your page(s) work and where the ID value comes from I can't give a speciic example, but, something like:
Have your page check ID to see if it hits your criteria, if it does, emit the javascript, but with some additional javascript that checks the response to the prompt and causes the page to re-submit but with confirmed=yes added on the querystring
Have your page check the querystring parameter "confirmed" to see if it's yes. If it is, THEN do the work
You can't do it this way. RegisterStartupScript just registers the script to be included when the page is finally rendered. After it is rendered (to HTML) then the html is sent to the browser. So when the user finally sees that popup, your code has long since finished.
EDIT:
See the answer by Mike C.: you need to move that confirm to just before the submit.
Page.ClientScript.RegisterStartupScript will register that script on the client. As far as I can see you are executing the if statement on the server. Could you please specify what confirm is not working mean? Is the alert box displaying but no effect should yes/no is pressed? If so, move the if ... else statement on the client. Anyway, I suggest that you replace RegisterStartupScriptBlock with this code:
ClientScript.RegisterClientScriptBlock
(this.GetType(), "confirm", "alert('do')", true);
I'm using DevExpress ASPxButton, and I was wondering how can I prevent the user from clicking the button more then once?
Basically it does an update/insert statement.
This can be done using the following code:
var buttonClicked = false;
function MyBtnClick(s,e){
if(buttonClicked) return;
buttonClicked = true;
// do something
}
<ASPxButton id="btn" runat="server">
<ClientSideEvents Click="function(s,e) { MyBtnClick(s,e); } "/>
</ASPxButton>
On the client side, you can disable it when it's clicked.
On the server side, my favourite approach is generally to send a nonce with the form data, and then reject duplicate nonces.
As always, client side validates in a fast and (hopefully) friendly way, server side validates for sure even if client side code suffers from some unexpected browser issue, or someone is deliberately messing things up.
Not sure about aspxbutton specifically but in general you will have something like this on the onclick attribute of the control.
onclick="this.disabled=true;"
In the code where you run the update query simply add to the start of the code:
ButtonNameOrID.Enabled = False // add ; to end if C#
Then at the end of the code, add:
ButtonNameOrID.Enabled = True // add ; to end if C#
This is will disable/enable the button from your C# or VB code.