Learning
Learning

Reputation: 20001

Confirm box in asp.net web form application

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

Upvotes: 1

Views: 20405

Answers (3)

Jason W
Jason W

Reputation: 13179

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?');" /> 

Upvotes: 1

Chris L
Chris L

Reputation: 2292

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>

Upvotes: 3

Arindam Nayak
Arindam Nayak

Reputation: 7462

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

Upvotes: 1

Related Questions