NashTech Blog

Data Annotations in ASP.NET Core MVC

Table of Contents

ASP.NET Core MVC provides a powerful mechanism called Data Annotations, which allows developers to easily specify validation rules, display formatting, and more, directly within the model class. These annotations are attributes that can be applied to model properties, providing a declarative way to define metadata about the data.

 

1. Required Attribute

The Required attribute specifies that a property must have a value. If a user submits a form without providing a value for a required field, the validation will fail.

public class Product
{
[Required]
public string Name { get; set; }

[Required]
public decimal Price { get; set; }
}

2. StringLength Attribute

The StringLength attribute specifies the maximum length of a string property.

public class Customer
{
[StringLength(50)]
public string Name { get; set; }
}

3. Range Attribute

The Range attribute specifies the minimum and maximum allowed values for a numeric property.

public class Employee
{
[Range(18, 60)]
public int Age { get; set; }
}

4. RegularExpression Attribute

The RegularExpression attribute allows you to specify a regular expression that the property value must match.

public class User
{
[RegularExpression(@"^[a-zA-Z0-9]*$")]
public string Username { get; set; }
}

5. Display Attribute

The Display attribute allows you to specify the display name for a property.

public class Book
{
[Display(Name = "Title")]
public string Name { get; set; }
}

Example

Let’s consider a simple ASP.NET Core MVC application that uses Data Annotations for validation.

Product Model:

using System.ComponentModel.DataAnnotations;

public class Product
{
public int Id { get; set; }

[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }

[Required(ErrorMessage = "Price is required")]
[Range(0, double.MaxValue, ErrorMessage = "Price must be greater than 0")]
public decimal Price { get; set; }

[StringLength(100, MinimumLength = 10, ErrorMessage = "Description must be between 10 and 100 characters")]
public string Description { get; set; }
}

Product Controller:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

public class ProductController : Controller
{
public IActionResult Create()
{
return View();
}

[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Save product to database
return RedirectToAction("Index");
}
return View(product);
}

public IActionResult Index()
{
var products = new List<Product>();
// Retrieve products from database
return View(products);
}
}

Product View (Create.cshtml):

@model Product

<form asp-action="Create" method="post">
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
</div>
<div>
<label asp-for="Price"></label>
<input asp-for="Price" />
<span asp-validation-for="Price"></span>
</div>
<div>
<label asp-for="Description"></label>
<textarea asp-for="Description"></textarea>
<span asp-validation-for="Description"></span>
</div>
<button type="submit">Submit</button>
</form>

In this example, the Product class uses various Data Annotations to specify validation rules for its properties. The Create action in the ProductController handles the form submission, and if the model state is valid, it saves the product to the database. Otherwise, it redisplays the form with validation errors.

Data Annotations in ASP.NET Core MVC provide a convenient way to define validation rules and other metadata for model properties, making it easier to create robust and reliable web applications.

Picture of sujitmeshram

sujitmeshram

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top