【发布时间】:2010-11-24 15:33:46
【问题描述】:
我一直在尝试遵循网络上的验证教程和示例,例如来自David Hayden's Blog 和官方ASP.Net MVC Tutorials,但我无法获得以下代码来显示实际的验证错误。如果我的视图看起来像这样:
<%@ 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... --%>
对于一个看起来像这样的模型类:
public class Parent
{
public String FirstName { get; set; }
public String LastName { get; set; }
public int Age { get; set; }
public int Id { get; set; }
}
每当我输入无效的 Age(因为 Age 被声明为 int),例如“xxx”(非整数)时,视图确实正确显示消息“编辑失败。正确错误并重试”,以及突出显示“年龄”文本框并在其旁边放置一个红色星号,表示错误。但是,ValidationSummary 不会显示错误消息列表。当我自己进行验证时(例如:下面的 LastName),消息显示正确,但 TryUpdateModel 的内置验证似乎在字段具有非法值时不显示消息。
这是在我的控制器代码中调用的操作:
[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);
}
我错过了什么?
【问题讨论】:
标签: c# asp.net-mvc validationsummary