有没有内置的方式来做到这一点。据我所知,MVC开发者故意忽略它,因为他们认为这会导致UI混乱。它还引入了一个问题:“你想如何输出它们?”
所以你必须制定你自己的帮助方法,它可以很容易地基于ValidationMessageFor
,例如 - 连接所有用逗号分隔的错误信息(未经测试,只是概念):
public static class ValidationHelpers
{
public static MvcHtmlString MultiValidationMessageFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
object htmlAttributes = null
)
{
var propertyName = ModelMetadata.FromLambdaExpression(
expression, htmlHelper.ViewData).PropertyName;
var modelState = htmlHelper.ViewData.ModelState;
if (modelState.ContainsKey(propertyName) &&
modelState[propertyName].Errors.Count > 1)
{
// We have multiple error messages
string messages = String.Join(", ",
modelState[propertyName].Errors.Select(e => e.ErrorMessage)
);
// Reuse the built-in helper that takes a string as the message:
return htmlHelper.ValidationMessageFor(
expression,
messages,
htmlAttributes as IDictionary<string, object> ?? htmlAttributes
);
}
// We only have a single message, so just call the standard helper
return htmlHelper.ValidationMessageFor(
expression,
null,
htmlAttributes as IDictionary<string, object> ?? htmlAttributes
);
}
}
或者你可以为每个做一个完整的验证消息<span>
(还未经测试):
// Only the multiple error case changes from the version above:
if (modelState.ContainsKey(propertyName) &&
modelState[propertyName].Errors.Count > 1)
{
StringBuilder builder = new StringBuilder();
// Build a complete validation message for each message
foreach (ModelError error in modelState[propertyName].Errors)
{
builder.Append(
htmlHelper.ValidationMessageFor(
expression, error.ErrorMessage, htmlAttributes
)
);
}
return MvcHtmlString.Create(builder.ToString());
}