# 7.1: Validation Messages

The code in this section adds success/failure messages for validation of note creation.

## Update the Create \[HttpPost] Method

1. Still in **ElevenNote.Web -> Controllers -> NoteController**
2. Change the `Create` \[Post] method to match this:

   ```csharp
        [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

1. Go to **ElevenNote.Web -> Views -> Note**
2. Open `Create.cshtml`
3. Notice the `ValidationSummary`
4. `ViewBag` is a way that communication could go to the view
5. Instead we will use `ValidationSummary`

## Add Model Error Message

1. Go back to **ElevenNote.Web -> Controllers -> NoteController**
2. Comment out the following code and add `ModelState.AddModelError...`, this way you can run the app and see the error message.

   ```csharp
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(NoteCreate model)
        {
            if (!ModelState.IsValid) return View(model);

            //var service = CreateNoteService();

            //if (service.CreateNote(model))
            //{
            //    return RedirectToAction("Index");
            //};

            ModelState.AddModelError("", "Note could not be created.");

            return View(model);
        }
   ```
3. Run the app and try to create a note. You should see the error message:

   ![Error](/files/-LAxNDKTfcUeHiE_2Zw7)
4. Let's stop the app so that we can fix this.

## Add Success Message

1. Un-comment out the lines from before
2. Inside the `NoteController` conditional that indicates the save was successful, add `ViewBag.SaveResult = "Your note was created.";`
3. Your code should look like this:

   ```csharp
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(NoteCreate model)
        {
            if (!ModelState.IsValid) return View(model);            

            var service = CreateNoteService();

            if (service.CreateNote(model))
            {
                ViewBag.SaveResult = "Your note was created.";
                return RedirectToAction("Index");
            };

            ModelState.AddModelError("", "Note could not be created.");

            return View(model);
        }
   ```

## Add a Bootstrap Error Message in the View

1. Click on the `Index()` method and type `CTRL M G`, this should take you to the `Index.cshtml` file
2. Or, go to **ElevenNote.Web -> Views -> Note -> Index.cshtml**
3. Add this `<div>` between the `<p>` and the `<table>`

   ```markup
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
       <div class="alert alert-success fade in" role="alert">
            @ViewBag.SaveResult
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
   ```
4. This uses a Bootstrap component, click [here](https://getbootstrap.com/docs/3.3/components/#alerts) to look at the docs.
5. The success message does not appear because of the `RedirectToAction`
6. RedirectToAction create ViewBag.Result to the following:
7. Back in the `NoteController.cs` file, change `ViewBag` to `TempData`

   ```csharp
         var service = CreateNoteService();

        if (service.CreateNote(model))
        {
            TempData["SaveResult"] = "Your note was created.";
            return RedirectToAction("Index");
        };
   ```
8. `TempData` removes information after it's accessed&#x20;
9. Go back to the `Index.cshtml` file
10. wrap your `<div class="alert...>` in the following conditional:

    ```markup
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>

    @if(TempData.ContainsKey("SaveResult"))
    {
        <div class="alert alert-success fade in" role="alert">

            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
            @TempData["SaveResult"]
        </div>
    }
    ```
11. `.ContainsKey` checks to see if that key is in the dictionary, but will not remove it.
12. Run the app, you should see this message when you create a note:

    ![Success Message](/files/-LAxNDxc-OFNWPwoR-cJ)
13. ![Git](/files/-LAwyxUd0dcYSLXYb-5s)

[Next,](/dotnet-201-elevennote/elevennote-parts-1-11/part-8-notedetail/8.0-notedetail.md) we'll work on the Note detail.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://eleven-fifty-academy.gitbook.io/dotnet-201-elevennote/elevennote-parts-1-11/part-7-create-refactor/7.1-validationmessages.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
