Advertise with us

How can we do validations in MVC?

Posted by  Manoj Bhatt
 1290  View(s)
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. 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

    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)
            return View("Save Sucessfully");
            return View("Student");

      Modified On Apr-11-2018 01:27:45 AM