I tried to follow the verification instructions and examples on the Internet, for example, David Hayden Blog and the official ASP.Net MVC Tutorials , but I can not get the code below to display the actual verification errors. If I have a view that looks something like this:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Parent>" %> <%-- ... content stuff ... --%> <%= Html.ValidationSummary("Edit was unsuccessful. Correct errors and retry.") %> <% using (Html.BeginForm()) {%> <%-- ... "Parent" editor form stuff... --%> <p> <label for="Age">Age:</label> <%= Html.TextBox("Age", Model.Age)%> <%= Html.ValidationMessage("Age", "*")%> </p> <%-- etc... --%>
For a model class that looks like this:
public class Parent { public String FirstName { get; set; } public String LastName { get; set; } public int Age { get; set; } public int Id { get; set; } }
Whenever I enter an invalid age (since Age is declared as int), for example, "xxx" (not an integer), the view correctly displays the message "Edit was unsuccessful. Correct errors and try again" at the top of the screen, and also highlighting the text box " Age "and placing a red star next to it, indicating an error. However, using ValidationSummary, a list of error messages is not displayed. When I do my own check (for example: for LastName below), the message is displayed correctly, but the TryUpdateModel built-in check does not seem to display the message when the field has an illegal value.
Here is the action called in my controller code:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult EditParent(int id, FormCollection collection) { // Get an updated version of the Parent from the repository: Parent currentParent = theParentService.Read(id); // Exclude database "Id" from the update: TryUpdateModel(currentParent, null, null, new string[]{"Id"}); if (String.IsNullOrEmpty(currentParent.LastName)) ModelState.AddModelError("LastName", "Last name can't be empty."); if (!ModelState.IsValid) return View(currentParent); theParentService.Update(currentParent); return View(currentParent); }
What did I miss?
source share