2012-02-16 66 views
1

一个字段中指定多个验证消息我有FormModel这样的:Asp.net mvc验证。如何在视图

public class Model 
{ 
    [Required] 
    [StringLength(10)] 
    public string Name { get; set; } 
} 

我想指定RequiredAttribute标签和StringLengthAttribute 2个不同的消息。我不想在验证属性中指定我的错误消息。我想在我的视图中指定它们。但在我看来,我只能做这样的事情:

@Html.TextBoxFor(x => x.Name) 
@Html.ValidationMessageFor(x => x.Name, "validation error") 

有人遇到这个问题吗? 在此先感谢....

回答

3

有没有内置的方式来做到这一点。据我所知,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()); 
}