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 characters. The text displayed in a label is normally the property name, but that can be overridden 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.
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.
Let’s add both types of validation to the Create view to see what it looks like.
<form asp-action="Create" method="post">
<div asp-validation-summary="All"></div>
<td><span asp-validation-for="Title"></span></td>
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>
Since no JavaScript validation libraries have been added to the application, you must validate 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.
if (ModelState.IsValid)
{
...
}
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();
}
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.
<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" />
using System.ComponentModel.DataAnnotations;
[Required]
public string Title { get; set; }
[Required, MinLength(3)]
[Display(Name ="Film Genre")]
[DataType(DataType.Password)]
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.
Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.
50% Complete
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.