ASP.NET MVC v1.0 source code
从微软,我发现,无论是偶然还是故意,都没有办法做我想做的事,至少在默认情况下是这样。显然,在调用UpdateModel或TryUpdateModel期间,如果整数验证(例如)失败,则不会在与ModelState关联的ModelError中为坏值显式设置ErrorMessage,而是设置Exception属性。根据MVC ValidationExtensions的代码,以下代码用于获取错误文本:
string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);
private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState) {
if (!String.IsNullOrEmpty(error.ErrorMessage)) {
return error.ErrorMessage;
}
if (modelState == null) {
return null;
}
// Remaining code to fetch displayed string value...
}
因此,如果模型错误。ErrorMessage属性为空(我在尝试将非整数值设置为声明的int时验证了这一点),MVC继续检查ModelState,我们已经发现它为null,因此任何Exception ModelError都会返回null。因此,在这一点上,我对这个问题的两个最佳解决方案是:
-
创建一个自定义验证扩展插件,当未设置ErrorMessage但设置了Exception时,该扩展插件会正确返回相应的消息。
-
还有其他想法吗?