The server code and the database now validate any data that is saved. The user can’t see this yet. This can be frustrating since records are not saved when the ModelState.IsValid is false. The user could get stuck in the edit page and not know why the Save button is failing. To solve this, we need to apply validation controls and client-side JavaScript to the edit page.

Basic validation messages are displayed in a <span> tag using the tag helper asp-validation-for. This will show a default message if any of the model annotations are violated. If you specified a custom ErrorMessage in your annotation, that displays instead. Here is a sample:

<div style="flex:1 0 auto;width:auto"> <input asp-for="Continent.ID" class="form-control" /> <span asp-validation-for="Continent.ID" class="text-danger"></span> </div>

Some client-side scripts are needed to handle the validation logic in the browser. These are provided by ASP.NET but must be added to each page that needs them. This is done in a @section which matches the @RenderSection in the Pages/Shared/_Layout.cshtml file.

For example, this @section is named OtherScripts and it would render some partial named _UsefulScriptsPartial:

@section OtherScripts { @{ await Html.RenderPartialAsync("_UsefulScriptsPartial"); } }

This might have a matching section in _Layout.cshtml like:

@RenderSection("OtherScripts", required: false)

In the Bootstrap CSS:

  • text-danger - make the message red



In Pages/Continents/Edit.cshtml, inspect the <label> and <input> groups.

Edit each form group to add a <span> to show the validation message. These are wrapped in a <div> that works with the flex grid. The <span> will show on a separate line in red (bootstrap text-danger). The hint has a sample that replaces the first <input> tag.

Also apply this to the Name <input>.


Add a @section to the bottom of the file that loads the jQuery validation JavaScript.

Inspect Pages/Shared/_Layout.cshtml to see where @section is placed in the rendered page.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?