Data Annotations in ASP.Net Core C# - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Wednesday, July 8, 2026

Data Annotations in ASP.Net Core C#

Data Annotations in ASP.Net Core C#

Screenshot from the tutorial
Screenshot from the tutorial

Understanding Data Annotations in ASP.NET Core

Data annotations are an essential part of model validation in ASP.NET Core, allowing developers to enforce rules and constraints on data models easily. In this tutorial, we will explore what data annotations are, how to use them effectively, and some practical examples to illustrate their use.

What Are Data Annotations?

Data annotations are attributes that can be applied to classes and properties in your C# models. They are part of the System.ComponentModel.DataAnnotations namespace and provide a way to specify metadata about the data model. This metadata can be used for validation, display, and formatting purposes.

Benefits of Using Data Annotations

Using data annotations offers several advantages:

  • Simplicity: They provide a straightforward way to enforce validation rules without requiring extensive configuration.
  • Readability: The rules are declared directly in the code, making it easier to understand the constraints on each property.
  • Integration: Data annotations integrate seamlessly with ASP.NET Core's model binding and validation framework.

Common Data Annotations

Here are some of the most commonly used data annotations:

1. Required

The Required attribute ensures that a particular property must have a value.

public class User
{
    [Required(ErrorMessage = "Username is required.")]
    public string Username { get; set; }
}

2. StringLength

The StringLength attribute restricts the length of a string property.

public class User
{
    [StringLength(50, MinimumLength = 5, ErrorMessage = "Username must be between 5 and 50 characters.")]
    public string Username { get; set; }
}

3. Range

The Range attribute specifies a numeric range that a property must fall within.

public class Product
{
    [Range(1, 1000, ErrorMessage = "Price must be between 1 and 1000.")]
    public decimal Price { get; set; }
}

4. EmailAddress

The EmailAddress attribute validates that a property contains a valid email format.

public class User
{
    [EmailAddress(ErrorMessage = "Invalid email address.")]
    public string Email { get; set; }
}

5. Compare

The Compare attribute is often used in scenarios like password confirmation to ensure two properties match.

public class UserRegistration
{
    public string Password { get; set; }

    [Compare("Password", ErrorMessage = "Passwords do not match.")]
    public string ConfirmPassword { get; set; }
}

Implementing Data Annotations in ASP.NET Core

To see data annotations in action, let’s implement them in a simple ASP.NET Core Web Application.

Step 1: Create a New ASP.NET Core Project

You can create a new ASP.NET Core project using the .NET CLI:

dotnet new mvc -n DataAnnotationsDemo
cd DataAnnotationsDemo

Step 2: Define Your Model

In the Models folder, create a new class called User.cs. Use the data annotations we discussed earlier to define properties:

using System.ComponentModel.DataAnnotations;

public class User
{
    [Required(ErrorMessage = "Username is required.")]
    [StringLength(50, MinimumLength = 5)]
    public string Username { get; set; }

    [EmailAddress(ErrorMessage = "Invalid email address.")]
    public string Email { get; set; }
    
    [Required(ErrorMessage = "Password is required.")]
    [StringLength(100, MinimumLength = 6)]
    public string Password { get; set; }
}

Step 3: Create a View for User Input

In the Views folder, create a new folder named User and add a Create.cshtml view.

@model DataAnnotationsDemo.Models.User

<form asp-action="Create">
    <div>
        <label asp-for="Username"></label>
        <input asp-for="Username" />
        <span asp-validation-for="Username" style="color:red;"></span>
    </div>
    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email" />
        <span asp-validation-for="Email" style="color:red;"></span>
    </div>
    <div>
        <label asp-for="Password"></label>
        <input asp-for="Password" type="password" />
        <span asp-validation-for="Password" style="color:red;"></span>
    </div>
    <button type="submit">Register</button>
</form>

Step 4: Handle Validation in the Controller

In your UserController, create a method to handle form submissions and validate the model.

using Microsoft.AspNetCore.Mvc;

public class UserController : Controller
{
    [HttpGet]
    public IActionResult Create() => View();

    [HttpPost]
    public IActionResult Create(User user)
    {
        if (!ModelState.IsValid)
        {
            return View(user);
        }

        // Save the user to the database (not implemented here)
        
        return RedirectToAction("Index");
    }
}

Conclusion

Data annotations in ASP.NET Core provide a powerful and convenient way to enforce validation rules on your data models. By using attributes like Required, StringLength, Range, EmailAddress, and Compare, you can ensure that your application handles user input correctly and securely.

With this understanding, you are now ready to implement data annotations in your ASP.NET Core applications effectively. Happy coding!

Another screenshot from the tutorial
Another view from the tutorial

Connect with SkillBakery Studios

Explore more tutorials, tools, and resources:

Posted by SkillBakery Studios

No comments:

Post a Comment

Post Top Ad