Introduction
This article will explain validation message and validation summary in ASP.NET MVC. We will understand it with examples.
- ValidationMessage
- ValidationMessageFor
- ValidationSummary
Step 1
Open Visual Studio 2015 or a version of your choice and create a table with some data.
Step 2
In Visual Studio, choose a web application project and give an appropriate name to your project.
Step 3
Select "empty template", check on the MVC checkbox, and click OK.
Step 4
Right click on models folder and “Add” Employee class,
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
-
- namespace MvcValidationMessage_Demo.Models
- {
- public class Employee
- {
- public int Id { get; set; }
-
- [Required(ErrorMessage = "Please enter name")]
- public string Name { get; set; }
-
- [Required(ErrorMessage = "Please enter position")]
- public string Position { get; set; }
-
- [Required(ErrorMessage = "Please enter salary")]
- public int Salary { get; set; }
- }
- }
Step 5
Right-click on the Controllers folder and add a controller.
A window will appear. Choose MVC5 Controller-Empty and click "Add".
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.
Home Controller Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcValidationMessage_Demo.Models;
-
- namespace MvcValidationMessage_Demo.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
-
- public ActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- public ActionResult Create(Employee employee)
- {
- if (ModelState.IsValid)
- {
-
- }
- return View();
- }
- }
- }
Step 6
Right-click the Index method in HomeController. The "Add View" window will appear with default index name checked (use a Layout page). Click on "Add".
The Html.ValidationMessage() is an extension method, that is a loosely typed method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
Validation Method Signature
- MvcHtmlString ValidateMessage(string modelName, string validationMessage, object htmlAttributes)
-
- @model MvcValidationMessage_Demo.Models.Employee
-
- @{
- ViewBag.Title = "Create";
- }
-
- <h4>Create New Employee</h4>
- @using (Html.BeginForm())
- {
- <div class="form-group">
- @Html.LabelFor(m=>m.Name)
- @Html.TextBoxFor(m => m.Name, new {@class = "form-control"})
- @Html.ValidationMessage("Name","Please enter name","text-danger")
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Position)
- @Html.TextBoxFor(m => m.Position, new { @class = "form-control" })
- @Html.ValidationMessage("Position", "Please enter position", "text-danger")
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Salary)
- @Html.TextBoxFor(m => m.Salary, new { @class = "form-control" })
- @Html.ValidationMessage("Salary","Please enter salary","text-danger")
- </div>
- <div class="form-group">
- <button type="submit" class="btn btn-primary">Submit</button>
- </div>
- }
In ValidationMessage, the first parameter is modelName method, which is a lambda expression to specify a property for which we want to show the error message. The second parameter validationMassage and the third parameter is for html attributes like css, style etc.
ValidationMessageFor
The Html.ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
ValidationMessageFor signature
- MvcHtmlString ValidateMessage(Expression<Func<dynamic, TProperty>> expression, string validationMessage, object htmlAttributes)
-
- @model MvcValidationMessage_Demo.Models.Employee
-
- @{
- ViewBag.Title = "Create";
- }
-
- <h4>Create New Employee</h4>
- @using (Html.BeginForm())
- {
- <div class="form-group">
- @Html.LabelFor(m=>m.Name)
- @Html.TextBoxFor(m => m.Name, new {@class = "form-control"})
- @Html.ValidationMessageFor(m=>m.Name)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Position)
- @Html.TextBoxFor(m => m.Position, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Position)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Salary)
- @Html.TextBoxFor(m => m.Salary, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Salary)
- </div>
- <div class="form-group">
- <button type="submit" class="btn btn-primary">Submit</button>
- </div>
- }
The ValidationMessageFor() method will only display an error if you have configured DataAnnotations attribute to the specified property in the model class.
ValidationSummary
The ValidationSummary helper method generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
The ValidationSummary can be used to display all the error messages for all the fields. It can also be used to display custom error messages.
Displaying all validation errors at one place using validation summary HTML helper
To display all errors at one place, use ValidationSummary() HTML helper.
- @Html.ValidationSummary(false, "Please fix the following error and then submit the form")
-
- @model MvcValidationMessage_Demo.Models.Employee
-
- @{
- ViewBag.Title = "Create";
- }
-
- <h4>Create New Employee</h4>
- @using (Html.BeginForm())
- {
- <div class="form-group">
- @Html.LabelFor(m=>m.Name)
- @Html.TextBoxFor(m => m.Name, new {@class = "form-control"})
- @Html.ValidationMessageFor(m=>m.Name)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Position)
- @Html.TextBoxFor(m => m.Position, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Position)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Salary)
- @Html.TextBoxFor(m => m.Salary, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Salary)
- </div>
- <div class="form-group">
- <button type="submit" class="btn btn-primary">Submit</button>
- </div>
- @Html.ValidationSummary(false, "Please fix the following error and then submit the form")
- }