10.0: NoteDelete
In this section, we'll write the code to get rid of a note.
Delete GET Method and View
Open
NoteController.csCopy the
Details(int id)methodPaste it underneath the
Edit(int id, NoteEdit model)methodChange the name to
Delete[ActionName("Delete")] public ActionResult Delete(int id) { var svc = CreateNoteService(); var model = svc.GetNoteById(id); return View(model); }Right click on
Delete(int id)and add a view:
Delete POST Method
Back in
NoteController.cs, create anActionResultto remove the note from the databaseThis will need a different name due to overloading issues
[HttpPost] [ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeletePost(int id) { return RedirectToAction ("Index"); }Add some validation to the code:
[HttpPost] [ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeletePost(int id) { var service = CreateNoteService(); service.DeleteNote(id); TempData["SaveResult"] = "Your note was deleted"; return RedirectToAction ("Index"); }Ignore the error for now, it will go away once we add the code below in the
NoteService
NoteService
Open
NoteService.csCreate a
Deletemethod under theUpdateNotemethod:public bool DeleteNote(int noteId) { using (var ctx = new ApplicationDbContext()) { var entity = ctx .Notes .Single(e => e.NoteId == noteId && e.OwnerId == _userId); ctx.Notes.Remove(entity); return ctx.SaveChanges() == 1; } }Run the app and make sure you can delete a note

You should get a message that your note was deleted

Open up your
dbo.Noteto confirm that the specified note was deleted.Before
After

Next, we'll change the date/time format
Last updated