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"); } }
Liked By
Write Answer
How can we do validations in MVC?
Join MindStick Community
You have need login or register for voting of answers or question.
Anupam Mishra
07-Feb-2016