【发布时间】:2015-12-14 22:59:42
【问题描述】:
我一直在尝试使用 MVC 的固有验证框架来显示验证错误。我正在为我的控制器使用以下代码:
[HttpPost]
public ActionResult SaveApplication(ApplicationModel application)
{
if (!ModelState.IsValid)
{
return View("New",application);
}
ApplicationBLL.SaveApplication(application);
return Content(string.Empty);
}
虽然我的观点看起来像:
<tr>
<td>Name</td>
@Html.ValidationSummary(true)
<td>@Html.TextBoxFor(m => m.Name)</td>
<td>@Html.ValidationMessageFor(m => m.Name, "Name is required")</td>
</tr>
下面是模型类的样子:
public class ApplicationModel
{
public int ApplicationId { get; set; }
public string ApplicationNumber { get; set; }
[Required]
public string Name { get; set; }
public DateTime EventDate { get; set; }
public string EventAddress { get; set; }
}
我的模型对 name 属性进行了 [Required] 验证,当我将调试器放在控制器上时,它识别出 ModelState 无效并返回视图,但我没有看到任何我的页面上的错误。因为这是我第一次使用 MVC 的验证框架,所以我可能遗漏了一些非常琐碎的事情。
我想补充一点,我用 Ajax Post 调用 Controller 会导致这种异常吗?
【问题讨论】:
-
不确定您的要求。您已经在视图中指定了验证消息(如“需要名称”),这就是将要显示的内容。您是否希望显示“这是一个测试”?
-
我删除了添加自定义错误的控制器代码。感谢您指出,这令人困惑。我的问题是,当我期望验证失败错误至少应显示在页面上的某个位置时,视图上没有显示任何内容
-
用
[Required(ErrorMessage = "Name is required")] public string Name { get; set; }装饰您的财产在视图中仅使用@Html.ValidationMessageFor(m => m.Name),在控制器中仅使用if (!ModelState.IsValid) { return View(application); }。如果您在 Name 控件中提交没有文本的表单,您将看到错误消息(并且如果启用了客户端验证并包含脚本 - 将显示该消息并且它甚至不会提交) -
请向我们展示您的
ApplicationModelviewmodel 课程。 -
@dai:添加了您要求的代码
标签: .net asp.net-mvc validation asp.net-mvc-4 modelstate