htmlhelper validationsummary ASP.NET MVC
In ASP.NET MVC, the Html.ValidationSummary
helper method is used to display a summary of all validation error messages for a form.
Here's an example of how to use Html.ValidationSummary
:
- Create a model class with validation attributes. For example:
public class Person { [Required(ErrorMessage = "Please enter your name.")] public string Name { get; set; } [Range(0, 120, ErrorMessage = "Please enter a valid age.")] public int Age { get; set; } }Source:www.theitroad.com
- In your controller, create an instance of your model and pass it to the view. For example:
public ActionResult Create() { var person = new Person(); return View(person); } [HttpPost] public ActionResult Create(Person person) { if (ModelState.IsValid) { // Save person to database return RedirectToAction("Index"); } return View(person); }
- In your view, use
Html.ValidationSummary
to display a summary of all validation error messages for the form. For example:
@model Person @using (Html.BeginForm()) { @Html.LabelFor(m => m.Name) @Html.TextBoxFor(m => m.Name) @Html.ValidationMessageFor(m => m.Name) @Html.LabelFor(m => m.Age) @Html.TextBoxFor(m => m.Age) @Html.ValidationMessageFor(m => m.Age) @Html.ValidationSummary() <input type="submit" value="Save" /> }
The Html.ValidationSummary
method will display a summary of all validation error messages for the form. If the model validation fails, the summary will be displayed at the top of the form, above the individual validation error messages. If the model validation succeeds, the summary will be empty. You can also specify a custom message for the summary by passing a string parameter to the Html.ValidationSummary
method. For example:
@Html.ValidationSummary("Please correct the following errors:")