in order to perform a delete using javascript and a pop-up, you need to:
1)Create an action in the controller like the following:
[HttpPost]
public void DeleteItem(int id)
By decorating the action method with the [HttpPost] annotation, you avoid the undesired behaviour of a user typing the URL /Home/Delete/1 because only a POST will invoke the action.
2)If you delete-item is part of a list of items, you need to bind to your items in the View a sort of id, using the custom HTML5 attributes, like the following:
@for (int i = 0; i < Model.Items.Count; i++)
{
<a href="#" class="delete-button" data-id="@Model.Items[i].Id">Delete</a>
}
3)Using jQuery, as an example, bind to your delete button(s) in the page a pop-up on click
$().ready(function () {
$(".delete-button").click(null, DeleteItem); //DeleteItem is the callback
return false;
});
We need to specify a callback that will handle the delete button click
4)Using for example jQuery UI dialog component:
Create HTML for your pop-up text
<div id="dialog-confirm" style="display:none;" title="Confirm">
<p>
<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
Are you sure you want to proceed?
</p>
</div>
Handle the delete button click and bind the dialog to the html text so that the popup will tell the user what you want
function confirmDeleteVersion() {
var recordToDelete = $(this).attr("data-id"); // now we need the data-id to retrieve the identifier for the item to delete
$("#dialog-confirm").dialog({
resizable: false,
height: 200,
modal: true,
buttons: {
"Delete": function () {
$(this).dialog("close");
$.post("/Home/Delete", { id : recordToDelete}, DeleteSuccessfull);
},
Cancel: function () {
$(this).dialog("close");
}
}
});
};
So, we get the id of the button
var recordToDelete = $(this).attr("data-id");
where "this" is the HTML element which caused the event to fire using
The below row is actually where we ask the Controller to execute the delete action, and we use the id of the record
$.post("/Home/Delete", { id : recordToDelete}, DeleteSuccessfull);
5) Because the jQuery post is asynchrounous, we need a callback to handle the result
function DeleteSuccessfull()
{
//Do what you want...
};
That's it... keep in mind that it's just an example and I'm using jQuery dialog component, while you could use something different.