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:
ViewBag vs ValidationSummary
Go to ElevenNote.Web -> Views -> Note
Open
Create.cshtml
Notice the
ValidationSummary
ViewBag
is 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
NoteController
conditional 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.cshtml
fileOr, 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
RedirectToAction
RedirectToAction create ViewBag.Result to the following:
Back in the
NoteController.cs
file, changeViewBag
toTempData
TempData
removes information after it's accessedGo back to the
Index.cshtml
filewrap your
<div class="alert...>
in the following conditional:.ContainsKey
checks 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