How can I implement a Delete and Cancel button in

2019-08-02 17:38发布

问题:

I have a form to delete a record. One the form I am using a delete button and when the button is clicked the form is submitted.

<input type="submit" value="Delete" />

How can I implement a cancel and check in the action if it is the delete or the cancel that has been clicked?

回答1:

You have to give the input a name. For example:

<input type='submit' value='Delete' name='action' />
<input type='submit' value='Cancel' name='action' />

And then in your Action:

[HttpPost]
public ActionResult Submit(string action) {
    if (action == "Delete") {
        // User clicked "Delete"
    } else {
        // User clicked "Cancel"
    }
}


回答2:

Do you really need to handle a cancel click event in your controller? You are probably just redirecting the user to a different page when they cancel, right? Javascript has worked pretty well for me:

<input type="button" value="Cancel" 
   onclick="window.location='<%: Url.Action("Details", new { id = Model.Id }) %>'" />


回答3:

Using jQuery (well, you could do it in just JavaScript too), you could do something like:

$('input[type="submit"]').click(function(e) {
    if(confirm('Are you sure?') {
        // do delete
    }
});


回答4:

My Intro to ASP.NET MVC 3 explains this. Make sure you don't delete on a GET.



回答5:

In regards to Stephan Walter's site...

MVC application

What about using using the [ChildActionOnly] attribute with some authentication in the ActionResult to protect against accidental deletes? What if you are using jQuery GET callbacks with an ActionResult that renders a PartialViewas he suggests that REST purists would defend the idea that GET requests should not change the state of your application? like:

//delete comment and make ajax callback
function del(aid, cid) {
    $.ajax("/Article/DelCom?AId=" + aid + "&" + "CId=" + cid, function (result) {
        $('#comments-partial').html(result);
    });

Or is this only applicable for links?