ASP.NET Core 2.2 For Beginners (Part 7): Data Annotations

Data Annotations

Data annotations are attributes you add to properties in a model, to enforce rules about them. You can specify that a field is required or must have a maximum number of charac­ters. The text displayed in a label is normally the property name, but that can be overrid­den with the [Display] attribute.

Many data annotations can be found in the System.ComponentModel.DataAnnotations namespace. You can specify one annotation per code line, or multiple annotations as a comma-separated list inside a set of square brackets.

[Required]
[MaxLength(80)]

Or

[Required, MaxLength(80)]

Below is a list of commonly used data annotations.

­­

Preparing the Create View for Validation

To validate the annotations in the browser, the view must be altered to display possible errors. You usually do this by adding a <span> or a <div> element decorated with the asp-validation-for Tag Helper, specifying which property it displays errors for. You can also add a validation summary that displays all errors as an unordered list inside a <div> element decorated with the asp-validation-summary Tag Helper.

Adding Validation to the Create View

Let’s add both types of validation to the Create view to see what it looks like.

  1. Open the Create
  2. Add a validation summary <div> at the top of the form.

<form asp-action="Create" method="post">
    <div asp-validation-summary="All"></div>

  1. Add validation to the Title Add a <span> decorated with the asp-validation-for Tag Helper inside a <td> element below the Title <input>.

<td><span asp-validation-for="Title"></span></td>

  1. Repeat step 3 for the Genre

 

The complete Create view after the changes:

@using AspNetCore22Intro.Models
@model AspNetCore22Intro.Entities.Video
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    ViewData["Title"] = "Create";
}

<h1>Create Video</h1>

<form asp-action="Create" method="post">
    <div asp-validation-summary="All"></div>

    <table>
        <tr>
            <td><label asp-for="Title"></label></td>
            <td><input asp-for="Title" /></td>
            <td><span asp-validation-for="Title"></span></td>
        </tr>
        <tr>
            <td><label asp-for="Genre"></label></td>
            <td><select asp-for="Genre"
                asp-items="Html.GetEnumSelectList<Genres>()"></select>
            </td>
            <td><span asp-validation-for="Genre"></span></td>
        </tr>
    </table>

    <input type="submit" value="Create" />
</form>

<div>
    <a asp-action="Index">Back to List</a>
</div>

Validating the Model on the Server

Since no JavaScript validation libraries have been added to the application, you must vali­date the model on the server. To enforce model validation in the HTTP POST Create action, you must check if the model is valid before taking any action. If the model is valid, the video will be added to the data source, otherwise it will re-render the view so that the user can change the values and resubmit.

The ModelState object’s IsValid property can be used in the HTTP POST action to check if the model is valid. Surround the code that creates and adds the video to the data source with an if-statement that checks the IsValid property value. Return the view below the if-block if the model state is invalid.

  1. Open the HomeController
  2. Add an if-block that checks the model state; it should surround all the code inside the HTTP POST Create

if (ModelState.IsValid)
{
    ...
}

  1. Return the view below the if-block.

return View();

The complete code for the HTTP POST Create action:

[HttpPost]
public IActionResult Create(VideoCreateEditViewModel model)
{
    if (ModelState.IsValid)
    {
        var video = new Video
        {
            Title = model.Title,
            Genre = model.Genre
        };

        _videos.Add(video);

        return RedirectToAction("Details", new { id = video.Id });
    }

    return View();
}

Adding Data Annotations in the Video Entity and VideoCreateEditViewModel Class

Data annotations added to an entity class can affect both the controls in a view and the database table it represents.

In the project you are building, the Video entity is used as the view model for the Create view. To enforce some rules on that model, you add attributes to its properties that restrict or enhance them.

Let’s implement some annotations in the Video entity model that alter how the controls in the view are rendered, and later restrict the database columns.

  1. Add <script> and <link> elements for CDN (Content Delivery Network) URLs to JQuery and Bootstrap, as well as for validation libraries at the end of the Index, Create and Details Using CDNs, you don’t have to add the files locally in your project. In an upcoming chapter, you will learn how to use the _Layout view to add global <script> and <link> elements.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/
    jquery-validate/1.19.0/jquery.validate.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/
    jquery-validation-unobtrusive/3.2.11/
    jquery.validate.unobtrusive.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/
    bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/
    twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

  1. Open the Video entity model.
  2. Add a using statement to the DataAnnotations namespace to get access to the data annotation attributes.

using System.ComponentModel.DataAnnotations;

  1. Add the Required annotation to the Title This will restrict the value in the database table to non-null values, and force the user to enter a value in the control, for the model object to be valid.

[Required]
public string Title { get; set; }

  1. Open the VideoCreateEditViewModel and repeat step 2 and 3.
  2. Save all files and switch to the browser. Navigate to the /Home/Create
  3. Click the Create button without entering a title. The validation message should appear beside the input field.
  4. Add the MinLength annotation, with a min length of 3, to the Title property in both the Video and VideoCreateEditViewModel

[Required, MinLength(3)]

  1. Save all files and switch to the browser. Navigate to the /Home/Create
  2. Enter 2 characters in the Title input field and click the Create The validation message should tell you that too few characters have been entered in the input field.
  3. Enter at least 3 characters in the Title input field and click the Create The video should be successfully added to the data source.
  4. Add the MaxLength annotation, with a max length of 80, to the Title property in both the Video and VideoCreateEditViewModel This will ensure that the Title property can have at most 80 characters when saved to the data source, and that the input control only will accept that many characters.
  5. You can use the Display annotation to change the label text for a property. Let’s change the text for the Genre property to Film Genre. Add the Display attribute to the Genre property in the Video Set its Name parameter to the text Film Genre. You only have to add the attribute to the Video model, since it only is applied to labels in a view.

[Display(Name ="Film Genre")]

  1. Save all files and switch to the browser. Navigate to the /Home/Create The label for the Genre select list should display the text Film Genre.
  2. Let’s try the DataType annotation next. Add it to the Title property in the Video class and select the Password This should display the entered text as password characters, typically dots or asterisks. Specifying a data type in the model can change its control’s appearance on some devices, and can even change the layout of the keyboard displayed on the device screen, when the control has focus.

[DataType(DataType.Password)]

  1. Save all files and switch to the browser. Navigate to the /Home/Create Enter text in the Title input field. It should be displayed as password characters.
  2. Remove the Password annotation and save the file.

Summary

In this chapter, you learned about different models that can be used with MVC, and how data annotations can be used to influence the labels and input controls, created with HTML and Tag Helpers in the view.

You also implemented validation checks on the server and displayed validation messages on the client.

Stay connected with news and updates!

Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.

Subscribe
Close

50% Complete

Two Step

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.