7.1: Validation Messages
The code in this section adds success/failure messages for validation of note creation.
Update the Create [HttpPost] Method
Still in ElevenNote.Web -> Controllers -> NoteController
Change the
Create[Post] method to match this:[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(NoteCreate model) { if (!ModelState.IsValid) return View(model); var service = CreateNoteService(); if (service.CreateNote(model)) { return RedirectToAction("Index"); }; return View(model); }
ViewBag vs ValidationSummary
Go to ElevenNote.Web -> Views -> Note
Open
Create.cshtmlNotice the
ValidationSummaryViewBagis a way that communication could go to the viewInstead we will use
ValidationSummary
Add Model Error Message
Go back to ElevenNote.Web -> Controllers -> NoteController
Comment out the following code and add
ModelState.AddModelError..., this way you can run the app and see the error message.Run the app and try to create a note. You should see the error message:

Let's stop the app so that we can fix this.
Add Success Message
Un-comment out the lines from before
Inside the
NoteControllerconditional that indicates the save was successful, addViewBag.SaveResult = "Your note was created.";Your code should look like this:
Add a Bootstrap Error Message in the View
Click on the
Index()method and typeCTRL M G, this should take you to theIndex.cshtmlfileOr, go to ElevenNote.Web -> Views -> Note -> Index.cshtml
Add this
<div>between the<p>and the<table>This uses a Bootstrap component, click here to look at the docs.
The success message does not appear because of the
RedirectToActionRedirectToAction create ViewBag.Result to the following:
Back in the
NoteController.csfile, changeViewBagtoTempDataTempDataremoves information after it's accessedGo back to the
Index.cshtmlfilewrap your
<div class="alert...>in the following conditional:.ContainsKeychecks to see if that key is in the dictionary, but will not remove it.Run the app, you should see this message when you create a note:


Next, we'll work on the Note detail.
Last updated