Created
January 13, 2012 18:56
-
-
Save bcalloway/1608077 to your computer and use it in GitHub Desktop.
ASP MVC AJAX delete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///////////////////////////////////////////////////////////////////////////////////// javascript | |
$('a.delete').live('click', function () { | |
var id = $('p#item-id').val(); | |
$.ajax({ | |
url: '/path/to/controller/delete', | |
type: "POST", | |
traditional: true, | |
data: { 'id': id }, | |
success: function (html) { | |
$(this).fadeOut('slow').remove(); //Hide deleted row in DOM | |
$('#partial-container').html($(html)); | |
} | |
}); | |
return false; | |
}); | |
///////////////////////////////////////////////////////////////////////////////////////controller action | |
// where "dataEntities" is your Data Context Entity and "Model" is your Model name. | |
////////////////////////////////////////////////////////////////////////////////////// | |
private readonly dataEntities db = new dataEntities(); | |
[AcceptVerbs(HttpVerbs.Post)] | |
public ActionResult Delete(int id) { | |
Model page = Model.GetPage(id, db); | |
db.Model.DeleteObject(page); | |
db.SaveChanges(); | |
var items = Model.GetItems(db); | |
return PartialView("_Items", items); | |
} | |
//////////////////////////////////////////////////////////////////////// the view | |
<p>Blah, blah blah........</p> | |
<div id="partial-container"> | |
@Html.Partial("_Items", Model) | |
</div> | |
//////////////////////////////////////////////////////////////////////// the PartialView _Items.chtml | |
@foreach (string item in Model) { | |
<p id="@item.id">@item.name <a class="delete">DELETE</a></p> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment