9.0: NoteEdit Model

NoteEdit Model

In this section, we code the model that will allow us to update a note.

  1. In the Solution Explorer, right click on ElevenNote.Models

  2. Select Add -> Class and name it NoteEdit.cs

  3. Make the class public

  4. Add the following properties.

namespace ElevenNote.Models
{
    public class NoteEdit
    {
        public int NoteId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }
}

UpdateNote Method

  1. Open NoteService.cs

  2. Create a new method called UpdateNote that returns a bool based on if the NoteId is in the database and the note belongs to the specific _userId:

     public bool UpdateNote(NoteEdit model)
     {
         using(var ctx = new ApplicationDbContext())
         {
             var entity = 
                 ctx
                     .Notes
                     .Single(e => e.NoteId == model.NoteId && e.OwnerId == _userId);
         }
     }
  3. Finish out the method:

     public bool UpdateNote(NoteEdit model)
     {
         using(var ctx = new ApplicationDbContext())
         {
             var entity = 
                 ctx
                     .Notes
                     .Single(e => e.NoteId == model.NoteId && e.OwnerId == _userId);
    
             entity.Title = model.Title;
             entity.Content = model.Content;
             entity.ModifiedUtc = DateTimeOffset.UtcNow;
    
             return ctx.SaveChanges() == 1;
         }
     }

Edit Method

  1. Open NoteController.cs

  2. Create an Edit() method under the Details(int id) method but above the NoteService method:

public ActionResult Edit(int id)
{
    var service = CreateNoteService();
    var detail = service.GetNoteById(id);
    var model = 
        new NoteEdit
        {
            NoteId = detail.NoteId,
            Title = detail.Title,
            Content = detail.Content
        };
    return View(model);
}

Next, we'll create the view for editing a note Git.

Last updated