简体   繁体   中英

CSHTML Confirm Delete prior to deleting database record

I'm working on updating a form for our website. At the beginning of the code I have an @{} code block that runs updates on a database.

I now need to be able to delete a record from that database when a Cancel button is clicked. Prior to doing that I need to confirm that the user actually wants to delete the record they have started.

In C# I could use a MessageBox or DialogBox with an OK and CANCEL option, but what can I use inside the @{} code to do the same thing? I'm afraid that if I use JavaScript that the record will still be deleted if the user clicks the Cancel button.

Here is my Cancel button code:

if(!Request["btnCancel"].IsEmpty()){
    var deleteCommand = "DELETE FROM [dbo] WHERE ID=@0";
    db.Execute(deleteCommand, Userid);
    Response.Redirect("~/");
}

Where dbo is the name of my database.

Thanks to @Shyju for tipping me off to the answer. It was much more simple than I had anticipated. I was using an input tag, and luckily, it does have a built in onclick="" attribute. I simply did the following:

<input type="submit" name="btnCancel"
    class="btn btn-default btn-large"
    value="Cancel Application"
    formnovalidate 
    onclick="return confirm('Are you sure you want to cancel your application?\n\nThis process cannot be undone, and any information you have entered will be lost.');"/>

Now when the button is clicked I get a prompt with an OK or CANCEL button. The OK button continues the posting action while the CANCEL button returns to the page without posting or modifying the page and it's contents.

I hope this helps someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM