9.1: NoteEdit View
Create the Edit
View
Edit
ViewNow we create the physical view for the NoteEdit
model.
Still in the
NoteController.cs
file, right click on theEdit(int id)
methodAdd a view as below:
Edit
Post Method
Edit
Post MethodBack in
NoteController.cs
, build an overloadedEdit
ActionResult under theEdit(int id)
method:[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, NoteEdit model) { return View(); }
Add some validation similar to the
ActionResult Create
to make sure theNoteId
matches:[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, NoteEdit model) { if(!ModelState.IsValid) return View(model); if(model.NoteId != id) { ModelState.AddModelError("", "Id Mismatch"); return View(model); } return View(); }
Continue to build out the method, displaying a message to the user with the result of their actions:
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, NoteEdit model) { if(!ModelState.IsValid) return View(model); if(model.NoteId != id) { ModelState.AddModelError("", "Id Mismatch"); return View(model); } var service = CreateNoteService(); if (service.UpdateNote(model)) { TempData["SaveResult"] = "Your note was updated."; return RedirectToAction("Index"); } ModelState.AddModelError("", "Your note could not be updated."); return View(model); }
Remove NoteId
from the Edit View
NoteId
from the Edit ViewGo to ElevenNote.Web -> Views -> Note -> Edit.cshtml
Delete lines 18-24, we don't need to see the
NoteId
, and it should not be editable.We will add a reference to this code, but make it hidden.
Add this line of code (starting with
@Html.HiddenFor...
) in place of the lines we deleted:@HtmlValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.NoteId) <div class="form-group">
Run the app and make sure you can edit a note, if so,
If you run from the
Edit.cshtml
file, you will get an error because the URL goes to /Note/Edit but not to a specific note id.Change the URL to remove /Edit to get to the index view which lists all the notes.
Next, we'll add the ability to delete a note.
Last updated