これを行う方法はありません。それは意図的に、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());
}