9.0: NoteEdit Model
NoteEdit
Model
NoteEdit
ModelIn this section, we code the model that will allow us to update a note.
In the Solution Explorer, right click on ElevenNote.Models
Select Add -> Class and name it
NoteEdit.cs
Make the class public
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
UpdateNote
MethodOpen
NoteService.cs
Create a new method called
UpdateNote
that returns a bool based on if theNoteId
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); } }
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
Edit
MethodOpen
NoteController.cs
Create an
Edit()
method under theDetails(int id)
method but above theNoteService
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 .
Last updated