1.5.1.Adding validation

  • 1.Add data annotation to the model

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

        [Required]
        [StringLength(255)]
        public string Name { get; set; }

        public bool IsSubscribeToNesletter { get; set; }

        public MembershipType membershipType { get; set; }

        [Display(Name = "Membership Type")]
        public byte membershipTypeId { get; set; }

        [Display(Name = "Date or Birth")]
        public string Birthday { get; set; }
    }
  • 2.Add ModelState in the controller

    public ActionResult Save(Customer customer)
    {
            if (!ModelState.IsValid)
            {
                var viewModel = new CustomerFormViewModel
                {
                    customer = customer,
                    MembershipTypes = _context.membershipType.ToList()
                };
                return View("CustomerForm", viewModel);
            }
  • 3.Add warning message to the view

    <div class = "form-group">
        @Html.LabelFor(m => m.customer.Name)
        @Html.TextBoxFor(m => m.customer.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.customer.Name);
    </div>

Last updated