How can I implement a Delete and Cancel button in MVC3?

别来无恙 提交于 2019-12-11 14:14:44

问题


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?



来源:https://stackoverflow.com/questions/8439394/how-can-i-implement-a-delete-and-cancel-button-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!