I was following along with a tutorial on how to implement validation in my MVC web application. Below is a snippet of my View for creating a new Student:
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
Here is a snippet of my controller code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ContosoUniversity.DAL;
using ContosoUniversity.Models;
namespace ContosoUniversity.Controllers
{
public class StudentController : Controller
{
private SchoolContext db = new SchoolContext();
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include =
"ID,LastName,FirstMidName,EnrollmentDate")] Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
My @Html.ValidationMessageFor(model => model.LastName)
works without a problem. Even @Html.ValidationSummary(false)
works to displays my field errors, as expected, but I don't want my field errors displayed. When I change false
to true
and include my custom message, the message does not show up when I run my code in the browser. I cannot figure out what is going on, and I've tried researching the answer on the web, but there is no answer that makes sense to me, even though I'm sure it has been answered somewhere. Can someone please provide me with a "layman's terms" solution to this problem?