This is how validation works.
Let's say you have the following model:
public class MyModel { [Required] public string MyProperty { get; set; } }
Note the Required attribute, which is a data annotation attribute that indicates that MyProperty is required.
MyModel used by the following view (MyView.cshtml):
@model MyNamespace.MyModel @using (Html.BeginForm("MyAction", "MyController")) { @Html.LabelFor(m => m.MyProperty) @Html.TextBoxFor(m => m.MyProperty) @Html.ValidationMessageFor(m => m.MyProperty) <input type="submit" value="Click me"> }
Then, when this form is submitted to the MyAction MyController action, your model will be validated. You need to check if your model is valid or not. This can be done using the ModelState.IsValid property.
[HttpPost] public ActionResult MyAction(MyModel model) { if (ModelState.IsValid) { // save to db, for instance return RedirectToAction("AnotherAction"); } // model is not valid return View("MyView", model); }
If the validation fails, the view will be displayed again using various errors that are present in the ModelState . These errors will be used and displayed by the ValidationMessageFor helper.
source share