ASP.NET MVC > Models

Mandatory model field in ASP.NET MVC

How to make a model field mandatory?

To mark a model property mandatory, we use [Required] attribute.


using System; 
using System.Collections.Generic; 
using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication1.Models { public class PersonalDetail { [Key] [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOpt ion.Identity)] public int AutoId { get; set; }
[StringLength(20, MinimumLength = 4, ErrorMessage = "Must be at least 4 characters long.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please write your LastName")] public string LastName { get; set; }
[Required] public int Age { get; set; } [Display(Name = "Is Active?")]
public bool Active { get; set; } } }

Notice the highlighted attribute at the top. 

  1. For LastName, we have written [Required] attribute with custom error message we want to show if user doens't input LastName field data.
  2. For Age, the default error message comes when user doesn't input the data.
Please see the output picture below.
 Views: 2929 | Post Order: 35

Write for us