Confirm Box in Asp.Net - javascript

CODE
protected void btnSelectInvioces_Click(object source, EventArgs
{
try
{
// some code here
if(a == b)
{
// open confirmation box
if(OK) // i click ok button of confirm box
{
// proceed further...
}
}
}
catch()
{ }
}
I need to have a Confirm box only when satisfying a condition from server side.
I tried using RegisterClientScript.
What is happening is, it is executing my whole code and then giving me pop up.
BUT, I want to open popup at certain point. When it opens, further code should not be executed unless and until I click OK/Cancel button of that confirmation box

Your confirm box is client side. And the code that you shown is server side.
You need ajax for this purpose. If you need help there then let me know.
Remember alert, confirm and other things that are offered by your browser is client side. In your javascript you can do something like this,
if(confirm("press OK"))
{ ajax call }
in ajax call you can execute your server side code that starts after your condition if(OK)

You can use Ajax Confirm button extender with full customization http://www.ajaxcontroltoolkit.com/ConfirmButton/ConfirmButton.aspx
Or if you want to call in between button click process with code condition then u can use
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ajax", "callconfirm()", true);
if you get ok then call with your ajax
if(confirm("OK")) { ajax call }

First add a hidden field, and set its value based on user pressed confirmation button
Html Markup:
<asp:HiddenField ID="HiddenField1" runat="server" />
Client side: Set the result in hidden field
function ConfirmMessage() {
if (confirm("Are you sure ?")) {
$("#HiddenField1").val("Yes");
} else {
$("#HiddenField1").val("No");
}
}
Code-behind: Retrieve the hidden field value and make your call
string confirmValue = HiddenField1.Value
if (confirmValue == "Yes")
{
// logic code here
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You pressed NO!')", true);
}

using javascript like this:
<script type="text/javascript">
function ConfirmBox() {
if (confirm("Continue?")) {
alert("Yes");
} else {
alert("No");
}
}
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
And in the code behind you can use ScriptManager.RegisterStartupScript like this:
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "ConfirmBox", "ConfirmBox();", true);
}

Implement Confirmation Dialog Box Using Javascript
Please refer given URL
http://www.freshcodehub.com/Article/47/implement-confirmation-dialog-box-using-javascript

Related

prevent postback in js for a webform dropdown

I am developping an asp.net webform application. In a page, I have a dropdown containing some values ("a","b","c",...). When I select a value in this dropdown, a server side event is raised and I write the selected value in my DB.
This is the code :
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="server_handler" AutoPostBack="True"/>
protected void server_handler(object sender, EventArgs e)
{
myUpdateMethod(this.myDdl.selectedValue);
}
This is working perfectly, but now I would like to ask a confirmation on my client side when a value is selected, does we really want to update the value in my db.
If we selected yes in my confirm dialog in js, we pursue and call the server like before, if not we stop the postback. But this is what I am not able to do, I can't stop the postback, this is what i've tried :
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="server_handler" AutoPostBack="True" onchange="confirmornot(event)"/>
function confirmornot(event)
{
var str = confirm("do you want to continue?")
if (!str)// the user select no and this is where I am trying to stop to calling the server handler function. Basically there, I want here nothing to happen
{
//solution 1
event.preventDefault();
//solution 2
event.stopPropagation() or event.stopImmediatePropagation()
//solution 3
return false or return true
}
None of these solutions worked, the server side function is called whatever I put, I think that is because of my autpostback="true" on my drodown, but if I remove
this, then I will be in the opposite problem, and my server side function will never be called.
Thanks in advance for your help
You may try this:
Make ClientIDMode="Static" to asp net dropdown so that you will have static id "myDdl" and also set autopostback to false
In confirmornot method instead of return statement, try
__doPostBack('myDdl');
i Have a hacky solution for you
HTMl
Add a hidden field
<asp:HiddenField runat="server" ID="hdntocheck" />
DDL Markup
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="server_handler" AutoPostBack="True" onchange="confirmornot()"/>
Js
function confirmornot() {
if (!confirm("do you want to continue?"))
{
hdntocheck.value = "false";
}
else {
hdntocheck.value = "true";
}
}
In Cs
protected void server_handler(object sender, EventArgs e)
{
if( hdntocheck.value =="true")
{
myUpdateMethod(this.myDdl.selectedValue);
}
}

Confirmation message from the ASP.NET code behind file

I have a login screen Login.aspx after login I want to show a confirmation message saying
"You are being redirected to the Demo page. Do you want to continue?",
if the user clicked yes, I need to redirect them to a demo page. Other wise redirect to another home page. How can I do this?
I want something like the following...
protected void Login_Click(object sender, ImageClickEventArgs e)
{
//some validation and calculations..
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirm('You are redirecting to Demo page ". Do you want to continue" ?');", true);
//My doubt is this
If(ok button clicked)
{
//redirect to demo page
}
else
{
//redirect to home page
}
}
You wont get the result of confirm on server side. You can call a javascript function RegisterStartupScript and put this confirm dialog in that function.
Although you can somehow send value of confirm on server side using postback of some ajax call but I do not see any reason for that.
Code behind
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "RedirectDecision();", true);
Html
<script type="text/javascript">
function RedirectDecision()
{
if(confirm('You are redirecting to Demo page ". Do you want to continue" ?'))
window.location = "http://www.yoururlFirst.com";
else
window.location = "http://www.yoururlSecond.com";
}
</script>
You can't do that. You can call a client side function by setting OnClientClick. If user will press confirm than code behind function will be called. Have a look at below example
<asp:Button ID="Button2" OnClick="Login_Click" OnClientClick="return UserConfirmation()" runat="server" Text="Login" />
function UserConfirmation() {
if(confirm('You are redirecting to Demo page ". Do you want to continue" ?'))
return true;
else
return false;
}
Here if user will press ok than code behind function will be called other wise it won't

ASP.NET redirect from event handler hot by button clicked by JavaScript

I have a problem with a page not redirecting during a postback.
I have an aspx-page with this content being part of it:
<td class="tdinput" align="right">
<asp:Button ID="ButtonFrigiv" runat="server" Text="Frigiv sag" CssClass="button"
OnClientClick="verifyReleaseOtherEmployeesCase()" />
<asp:Button runat="server" ID="ButtonFrigivHidden" OnClick="ButtonFrigiv_Click"
Style="display: none;" UseSubmitBehavior="true" />
</td>
The page also contains various UpdatePanels, however the above code is not included in one.
As it is seen there's a button being displayed, which calls the following JavaScript:
function verifyReleaseOtherEmployeesCase() {
var logonUser = document.getElementById('<%= HiddenLogonUser.ClientID %>');
var lockedBy = document.getElementById('<%= HiddenLockedBy.ClientID %>');
var button = document.getElementById('<%= ButtonFrigivHidden.ClientID %>');
if (logonUser.value == lockedBy.value) {
button.click();
}
else if (confirm("Danish confirm message")) {
button.click();
}
else {
return;
}
}
So basically this JavaScript locates the 2nd button above (which is not being displayed to the user) and clicks it.
When the button is clicked the following event handler is reached on the server:
protected void ButtonFrigiv_Click(object sender, EventArgs e)
{
NyeSagerDAC.FrigivSag(SagID, LogonUser);
Response.Redirect(LastList);
}
Where LastList is a string containing the page which was the entry point for the current page (there are multiple entry points).
The server method is reached and the first line in the method is executed perfectly, however the page is not redirected.
I have done some testing regarding whether it might have been considered an AJAX-callback (which doesn't allow redirects) using the following code in the event handler:
HttpRequest request = HttpContext.Current.Request;
string header = request.Headers["X-MicrosoftAjax"];
The content of the string header is empty and the Page_Load is called after the event handler is done. So I don't think this is the problem.
I have also tried to register a startup script to have the page redirect itself instead. This has been tried in various ways:
Page.ClientScript.RegisterStartupScript(GetType(),"redirect",
"window.location.href='" + LastList + "'");
And
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect",
"window.location.href='" + LastList + "';", true);
However none of this seems to work.
The only thing I have got to work was when I removed the confirm() part of the JavaScript and had it just click the button. This resulted in the page being correctly reloaded. However, I need to ask the user actually wants to unlock another employee's task.
So I think my question is: How can I get the page to redirect? Alternatively, how can I modify the JavaScript to still ask the user to confirm and not stopping the redirect from working?
The solution is coded in .NET 4.0
Thanks in advance.
Your js function is named verifyReleaseOtherEmployeesCase but in the OnClientClick it says verifyReleaseOtherWorkersCase, assuming that is a typo you also need to prevent the first button from performing a postback.
Notice the return of false in the js function and the return in the OnClientClick
function verifyReleaseOtherEmployeesCase() {
var logonUser = document.getElementById('<%= HiddenLogonUser.ClientID %>');
var lockedBy = document.getElementById('<%= HiddenLockedBy.ClientID %>');
var button = document.getElementById('<%= ButtonFrigivHidden.ClientID %>');
if (logonUser.value == lockedBy.value) {
button.click();
}
else if (confirm("Danish confirm message")) {
button.click();
}
return false;
}
<asp:Button ID="ButtonFrigiv" runat="server" Text="Frigiv sag" CssClass="button"
OnClientClick="return verifyReleaseOtherEmployeesCase()" />

OnClientClick OnClick

In my asp page, I take a screenshot of the client's desktop with an applet and ask them to send it to the server with a single click of a LinkButton. I use runApplet() function to call my applet to capture the screen and assign the strings value to a hidden value. (picture is stored as base64 string) Until here, everything works perfect! However, SendLinkButton_Click doesnt seem to be executing!
This is my link button.
<asp:LinkButton ID="SendLinkButton"
OnClientClick="runApplet(); return false;"
OnClick="SendLinkButton_Click"
Visible="false"
CssClass="portal-arrow portal-button"
runat="server">Send</asp:LinkButton>
This is my Javascript function
function runApplet() {
var msg = document.capture.capture();
var hiddenControl = '<%= inpHide.ClientID %>';
document.getElementById(hiddenControl).value = msg;
}
and this is what's inside of SendLinkButton_Click
protected void SendLinkButton_Click(object sender, EventArgs e)
{
Server.Transfer("Preview.aspx", true);
}
when I put the javascript function to a LinkButton's OnClientClick, and execute this "SendLinkButton_Click" with another LinkButton. It works perfect! But I want them to work with just one click!
Please help!
Your client click is returning false so no postback will be made to the server after this point.
Try changing:
OnClientClick="runApplet(); return false;"
To
OnClientClick="runApplet();"
Remove return false from the OnClientClick attribute. If you return false from it, the postback will not execute.

Conditional confirm prompt in asp.net code behind

I have looked around for a way of implementing this. Here is a pseudocode representation of what I have:
bool hasData = ItemHasData(itemid);
Confirm = "false"; // hidden variable
if (hasData)
{
//Code to call confirm(message) returns "true" or "false"
if (Confirm == "true")
{
//Delete item
}
else if (Confirm == "false")
{
return;
}
}
The code to call confirm uses a asp:Literal control and sets it equal to the confirm. I can get the popup but only after the function exits. And it does nothing with the conditions after that.
The general consensus seems to be that calling the javascript at that specific line is impossible (makes sense due to the server side/client side gap), but how can I achieve this? I tried using the ConfirmButtonExtender from the ASP.NET AJAX Toolkit but I couldn't interact with the confirmbuttonextender object from the code behind when the object is set to runat="server".
edit:
Sorry, I did miss those tidbits. Thanks Icarus.
The control itself is the GridView (the pseudo version is actually from the gvData_RowCommand function)'s rowcommand. The first check looks to see if the CommandName is DeleteItem and if so goes into this.
The gvData's columns are set based off a list of headers (and the dataset) passed as the table it is working against is for multiple items with different required information. The gvData's data is there, I just need to get a Yes/No (or in reality it'll end up being Ok/Cancel) dialog to verify they want to delete the item when there is data.
One method I end up using in some situations is to have a Panel that displays the Confirm / Cancel buttons. This avoids the need to handle JavaScript events and uses ASP.NET entirely.
<asp:Panel ID="pDeleteConfirm" runat="server"
CssClass="AlertDialog"
Visible="False">
<p>Do you wish to delete the selected record?<br />
<asp:Button ID="btDeleteYes" runat="server" OnClick="btDelete_Click" Text="Delete" />
<asp:Button ID="btDeleteNo" runat="server" OnClick="btDelete_Click" Text="Cancel" />
</p>
</asp:Panel>
<asp:GridView ID="gvData" runat="server"
AutoGenerateColumns="False"
CssClass="GridView"
DataKeyNames="ID"
DataSourceID="sqlData"
EmptyDataText="There is no data entered in the system."
OnRowDeleting="gvData_RowDeleting">
......
</asp:GridView>
I use the OnRowDeleting event to show the Panel
protected void gvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// Show confirmation dialog
pDeleteConfirm.Visible = true;
// Select the row to delete
gvData.SelectedIndex = e.RowIndex;
// Cancel the delete so the user can use the confirm box
e.Cancel = true;
}
Handle the button Click events
protected void btDelete_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
switch (bt.ID)
{
case "btDeleteYes": // they confirmed a delete
sqlData.Delete();
break;
case "btDeleteNo": // they clicked cancel
// Do nothing
break;
default:
throw new Exception("Unknow button click in btDelete_Click");
}
// clear selection and hide the confirm box
gvData.SelectedIndex = -1;
pDeleteConfirm.Visible = false;
}
This isn't JavaScript but you can add in some UpdatePanels to do AJAX work on it.
Just one method to do it through ASP.NET rather than JavaScript handling.
The job of your code-behind is to render HTML out to the browser. It does this, and then the socket is closed and your server side code is no longer executing.
You'll have to implement this logic using a Javascript function on the client side.
Are you attempting to warn the user if there's data loaded before they take a certain action? Or perhaps before they try to leave the page? You'll have to popup the alert using script when that action happens on the page.

Categories

Resources