Confirm box in asp.net web form application - c#

I want to give user warning with confirm message box if they want to save without uploading image.
Code fires when user click on save button
if (string.IsNullOrEmpty(obj.Image)) {
obj.Image= null;
//Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "alert('Please Upload Image!');", true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "confirm('Are you sure you want to save without uploading images?');", true);
}
Above logic for was for showing confirm box but it doesn't show.
Besides that, how can I trap if user clicked on Yes or No button?
so that i can fire related code accordingly.
Update:
I am able to show confirm box with following code
Page.ClientScript.RegisterStartupScript(this.GetType(), "msgbxConfirm", "confirm('Are you sure?');", true);
But i am not sure how i am going to trap the YES or No event

To handle the result of a confirm popup box - check the return value.
If OK is clicked it will return true, else it will return false.
EG:
if(confirm('test')) {
alert('ok clicked')
} else {
alert('cancel clicked or closed popup')
}
JSFiddle example code in action
EDIT: comments
To resubmit the form if the user clicks OK on the confirm dialog something like this is what you need:
Codebehind:
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"msgbxConfirm",
"doConfirm();",
true
);
aspx page:
<script type=text/javascript>
function doConfirm() {
if(confirm('Are you sure?') {
document.getElementById(<id_of_form_submit_button>).click();
}
}
</script>

One thing i am adding here, you can not get the confirm result in server side code, you have to write that code in JS side. So to maintain it in better manner, you can use following JS in aspx.
function ConfirmAndExecute()
{
if(confirm("Are you sure?"))
{
OnConfirm();
}
else
alert("you missed !")
}
function OnConfirm()
{
// JS Code to handle post confirm operation
}
And in server side, page_load, use following.
Page.ClientScript.RegisterStartupScript(this.GetType(), "msgbxConfirm", "ConfirmAndExecute();", true);

You could also just add an onclick client script event handle to prevent submission of the form unless the confirmation is true so you don't have to deal with the script registration. Just add the code below into your asp:button definition
<asp:Button id="btnSave" Text="Save" runat="server" OnClientClick="return confirm('Are you sure?');" />

Related

OnClientClick custom message box before Onclick event handler not working

I wanted to have a Custom Message Box OnClientClick . If the User Selects Yes then the Onclick Event handler in the C# code should get trigger. But somehow i am not able to do this using ASP.net and jquery.
As of now what is happening
Only C# code is triggered
What i was expecting
ClientSide Confirmation message (If User Clicks "YES" ) Then Server-side
code triggers.
My HTML
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSubmit" Text="submit" runat="server" OnClick="btnDelete_Click"
OnClientClick="if(!ShowDeleteFormConfirmation()) {return false;};" />
</div>
</form>
Jquery
function ShowDeleteFormConfirmation() {
var confirmationMessage,
dlgButtons = {
"No": function () {
$(this).dialog("close");
return false;
},
"Yes": function () {
$(this).dialog("close");
return true;
}
};
confirmationMessage = "This form has already been assigned and will be marked as deleted.";
var $panelContainer = $("<div>" + confirmationMessage + "</div>").appendTo('body');
$panelContainer.attr("title", "Confirmation to delete a form");
var myPos = [$(window).width() / 2 - 100, 50];
$panelContainer.dialog({
modal: false,
draggable: false,
position: myPos,
button: dlgButtons
});
}
C# ////OnClick
protected void btnDelete_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Delete button clicked.');", true);
} ```
This is what i wanted to implement.
http://jsfiddle.net/y5z01nbr/
Thanks for having a look.
Ok, while your code would work if you used "confirm" in the js code, that's because alert() and confirm() HALTS the calling code.
However, today, near ALL WEB code libraries are written to NOT halt, and NOT freeze up the browser. And jQuery is one such system. (it does not HALT the code). While I could introduce the concepts of await - that's becoming a wee bit too complex for this POST.
So, what this means:
the jQuery code does NOT halt,
and thus when you click on the button,
the client side code runs WITHOUT halting
and thus the button click (server side code) will
ALSO run right away - not waiting.
So, in the case of a jQuery dialog? You can't HALT the code. this means you have to flip this backwards. The jQuery dialog is to be displayed, AND THEN you have to call/run/click on that server side button. So, you have to add a new button, and use style="display:none" ot the existing button. Then display the dialog, and based on the answer you THEN click on (call) that origional button you have/had now.
The code will thus look like this:
<div>
<asp:Button ID="btnSubmit" Text="submit" runat="server" OnClick="btnDelete_Click"
Style="display:none" clientIDmode="static" />
<asp:Button ID="btnSubmitX" Text="submit" runat="server"
clientIDmode="static" OnClientClick="ShowDeleteFormConfirmation();" />
<\div>
So I dropped in another button - no server behind code. Hide first button with display none, and removed the client click. I moved the client click to 2nd button.
Now, we can do this:
dlgButtons = {
"No": function () {
$(this).dialog("close");
},
"Yes": function () {
$(this).dialog("close");
$('#btnSubmit').click();
}
};
So what we do is launch the dialog. And based on yes, then we click our button. If you choose no, then the dialog is dismissed, but no other action need take place.
A a GENERAL hard and fast rule?
Your browser code is RARE these days blocking code - calling a jQuery.ui dialog and in fact most of these newer UI controls? The code does NOT wait, does NOT halt. And this means you can't use the return true/false to control if the server side event stub will run or not (you can use js confirm(), but not jQuery, since it don't wait, nor halt the code).

Obtain Confirm Answer upon submission

In my C# code, I have presented a confirm box to the user using the following code:
string confirmMsg = "All the cause data will be permanently removed. Are you sure you want to continue";
ClientScript.RegisterStartupScript(Page.GetType(), "TWCL Issue Mgmt System", "confirm('" + confirmMsg + "');", true);
I am trying to get the answer (YES or No) into a boolean or some other variable so that I can execute other code based on the answer given. So I would like something like this:
bool x = ClientScript.RegisterStartupScript(Page.GetType(), "TWCL Issue Mgmt System", "confirm('" + confirmMsg + "');", true);
if(x)
{
/*Exceute the rest of the code here*/
}
else
{
/*do postback*/
}
Any ideas on how to get the YES/NO answer from the confirm box?
Create a hidden field on the form. Write the answer of the question in the hidden field with some javascript. Read the value of the hidden field in the code behind.
The startup script that you are registering will run when the web page is displayed, before the user has had a chance to interact with it. A confirmation prompt at this time will likely be confusing.
It's more usual to use the OnClientClick property of a button that is doing the postback:
<asp:Button ...
OnClientClick="return confirm('Are you sure?');"
/>
so that the confirmation prompt is only displayed when the user attempts to post.

Show a confirmation/dialogbox in asp.net(c#)

Functionality I need to achieve is:
Confirmbutton_Click
Show a popup/dialogbox:
On click of Yes, I need to validate Email-Id and other personal details submitted.
If validation fails, show error messages and return false.
If email-id and other details are correct, then hide/show few Divs.
I had achieved this functionality in jQuery but now I am supposed to do it in server side. Firstly because the Divs were not showing up each time correctly and secondly due to security concern.
The suggestions I got on googling ask to write complete code (in script tag) at server side. That would be too much as I need to validate many fields.
Also, is there a way I can just do the validations at client side and come back to server side and show my Divs depending upon the validation result ? The client script will be executed before server side, so it is achievable.
I don't want to create a new popup page for this.
If anyone could help me with correct code or pointers to one, how to validate and show divs(showing div to be done from server side).
UPDATED:
I am midway, if anyone could help me any:
In page load(not post back) I hv added:
btnConfirm.Attributes.Add("onclick", "if(confirm('Confirm - Are you sure you want to go ahead.')) onConfirm(); else return false;");
In jQuery code i have added validations as:
function onConfirm() {
//Check if email-id is not blank, else show message and return to the page
if (isBlank($('#emailAddress').val()) == false) {
$('#errorBlankEmail').show();
return false;
}
}
//Text validation functions
function isBlank(valueSent) {
if ($.trim(valueSent) == "")
return false;
else
return true;
}
and the button code as:
<asp:Button ID="btnConfirm" runat="server" Text="Confirm" onclick="Confirm_Click" />
And the server side code for this:
protected void Confirm_Click(object sender, EventArgs e)
{
divConfirm.Visible = true;
}
Now when I click on button, it works until I validate and validation fails, it executes the server side code. Is there a way where I can avoid the server-side code if result is false in client click code ?
You may want to try using http://www.telerik.com/ ASP.net AJAX controls, or Ajax Control Toolkit Modal Extender. Ive used both and they are exactly what your after.
I woudn't suggest to do it this way , but maybe this will point you to better solution.
From server side as you mentioned you can use static function
var script = #"<script> $("#somediv").dialog() </script>", false);
ClientScript.RegisterClientScriptBlock(GetType(), "some", , false);
(#somediv) is encaplulated with user control and contains all validation logic.
The problem is server validation of your div , since after postback on div ( on server side validation) your div will be closed , and again you need to pup it up from server ,
This approach will mess up things ... I'd use new popup window that will return result.
you won't get a confirmation on the server. the server has not concept of user interaction within the request/response. it can only receive the request, process it, and send a response.
what you can do is send a request to generate a response which will ask for the user to confirm. the user would then click "yes" which will create another request. the server will receive the request, process the request and send a response.
but what you cannot do is ask the user to confirm the request while processing it on the server. that confirmation must have already been done.
you can validate the request the request on the server, but that is just standard validation. nothing fancy to do there.
you can use jQuery ui Dialog - Modal Confirmation
and on confirm use __doPostback to fire the event 'Confirmbutton_Click'
It is just another way, but it won't be as easy as telerik controls..
<script>
$(function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Confirm": function() {
$( this ).dialog( "close" );
__doPostBack('#<%= Confirmbutton.UniqueID %>', null)
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
And as html,
<div id="dialog-confirm" title="Empty the recycle bin?">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
<asp:button id="Confirmbutton" runat="Server" OnClick="Confirmbutton_Click" style="display:none;" />

Implementing javascript confirm box in code behind on drop down box's selected index change event firing

Inside my boxLang_OnSelectedIndexChanged() event I got this :-
if (txtbox1.Text != "" && txtbox2.Text != "")
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "confirm('Changing the language will clear the text in the textboxes. Click OK to proceed.');", true);
txtbox1.Text = "";
txtbox2.Text = "";
}
Now what is happening is that. When I select a different item from the drop down list this confirm box does show up BUT it first clears the content of the text boxes and then this confirm box appears. What I want is that the textboxes content should be cleared ONLY when OK is clicked.
What am I doing wrong? Please help.Thanks.
edit
#jgauffin
** I typed return where you have. Now what is happening is that its just clearing the textboxes right away..didn't even show the confirm box this time! Whats wrong now?? Please reply..thnx**
edit 2
I tried as follows:-
Inside my BindDropDown() method I added :-
dropdownbox1.Attributes.Add("onChange","DisplayConfirmation()");
then in my aspx page I have added the following script as follows:-
<script type="css/javascript">
function DisplayConfirmation() {
if (confirm('Changing the language will clear the text in the textboxes. Click OK to proceed.')) {
__doPostback('dropdownbox1','');
}
}
</script>
This function is not getting called when drop down's selected index is changed. What's wrong?
edit 3:-
ok I changed the line of code as follows:-
dropdownbox1.Attributes.Add("onchange", "javascript:return DisplayConfirmation()");
Still wont work. I am new to JavaScript and all so having problems. Help will be much appreciated.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "return confirm('Changing the language will clear the text in the textboxes. Click OK to proceed.');", true);
return is needed to break the process on cancel.
That's not going to work. You're posting back to the server, then registering the javascript confirm code, and then clearing content. The javascript confirm box will only actually appear once the page has reloaded, by which time you've already cleared the textbox values. It's like you're confusing clientside and server side programming. Client side code like javascript will only execute when the server has finished doing it's thing and the page is loaded.
What you need is this answer, probably:
DropdownList autoposback after client confirmation

confirm message box

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);

Categories

Resources