Delete with a [HttpPost] action method only
I want to provide the ability to delete a record, but only with an [HttpPost] action method, I mean, I don't want another view to confirm the deletion, only a javascript Confirm would be good.
The problem is that since I didn't provide an [HttpGet] action method, the controller can't direct the URL to the [HttpPost] action method, rather it gives 404 Not Found response when I hit the delete link.
Here is my action method:
// Note that there is no [HttpGet] delete action method
[HttpPost]
public ActionResult Delete(string name)
{
var village = Villages.FirstOrDefault(v => v.Name =开发者_如何学C= name && v.Deleted == false);
if (village == null)
return View("Error");
village.Deleted = true;
dc.SubmitChanges();
return RedirectToRoute(new { action = "Index" });
}
Create a hidden form with the delete link as action. Submit it when the user confirms:
<form method="post" id="deleteForm" action="">
</form>
<script type="text/javascript">
$('document').ready(function() {
$('a.delete').click(function(){
if (confirm('You sure?')) {
$('#deleteForm').attr('action', uri);
$('#deleteForm').submit(); //jquery
}
return false;
});
});
</script>
<a href="/user/remove/5" class="delete">Delete</a>
Update
Converted script to jquery. All you need to do is to add the form, the script and the "delete" class to your delete links. The form handling is done automatically for all links.
I think you want to use RedirectToAction() which will get the browser to make the appropriate GET requets to whatever controller/action you specify. This also mitigates the risk of the user accidently submitting the submit request twice by hitting refresh on the browser and re-submitting the POST.
精彩评论