HOW CAN WE DO VALIDATIONS IN MVC?

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
 693  View(s)
Ratings:
Rate this:
Hi Everyone,
Please give me a example, how to apply validation in ASP.NET MVC 4.Can anyone give me a solution.

Thank you.
  1. Anupam Mishra

    Post:135

    Points:949
    Re: How can we do validations in MVC?

    We are implementing validation in MVC is by using data annotations. Data annotations are nothing but attributes which can be applied on model properties. For example, we have a simple Student class with a property StudentFullName.
    This StudentFullName property is tagged with a Required data annotation attribute. In other words if this model is not provided Student FullName, it will not accept it.

    public class Student
    {
        [Required(ErrorMessage=" Student FullName is required")]
        public string StudentFullName
        {
            set;
            get;
        } 
    }  

    For display of validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

    @using (Html.BeginForm("StudentFullName", "Home", FormMethod.Post))

    @Html.TextBoxFor(m => m. StudentFullName)
    @Html.ValidationMessageFor(m => m. StudentFullName)
    .....
    }

    Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.

    public ActionResult StudentFullName(Student obj)
    {
        if (ModelState.IsValid)
        {
            obj.Save();
            return View("Save Sucessfully");
        }
        else
        {
            return View("Student");
        }
    }

      Modified On Feb-08-2016 09:53:50 PM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!