10.0: NoteDelete

In this section, we'll write the code to get rid of a note.

Delete GET Method and View

  1. Open NoteController.cs

  2. Copy the Details(int id) method

  3. Paste it underneath the Edit(int id, NoteEdit model) method

  4. Change the name to Delete

         [ActionName("Delete")]
         public ActionResult Delete(int id)
         {
             var svc = CreateNoteService();
             var model = svc.GetNoteById(id);
    
             return View(model);
         }
  5. Right click on Delete(int id) and add a view:

    Delete View

Delete POST Method

  1. Back in NoteController.cs, create an ActionResult to remove the note from the database

  2. This will need a different name due to overloading issues

     [HttpPost]
     [ActionName("Delete")]
     [ValidateAntiForgeryToken]
     public ActionResult DeletePost(int id)
     {
         return RedirectToAction ("Index");
     }
  3. 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");
     }
  4. Ignore the error for now, it will go away once we add the code below in the NoteService

NoteService

  1. Open NoteService.cs

  2. Create a Delete method under the UpdateNote method:

     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;
         }
     }
  3. Run the app and make sure you can delete a note

    Delete

  4. You should get a message that your note was deleted

    Delete Message

  5. Open up your dbo.Note to confirm that the specified note was deleted.

    Before

    Before

    After

    After

  6. Git

Next, we'll change the date/time format

Last updated