【问题标题】:Custom ValidationMessageFor and type of error自定义 ValidationMessageFor 和错误类型
【发布时间】:2012-10-25 11:56:10
【问题描述】:

有没有办法使用 ModelState 和模型进行验证,以确定错误的类型?

示例:

[必填]

我想制作一个自定义的 ValidationMessageFor,并在其中确定错误是 [必需] 还是其他类型的错误。

我正在使用 DataAnnotations 和 CodeFirst。

已经是从开始实现的代码:

public static MvcHtmlString MyValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
    var Validacao = "";       
    if (helper.ViewData.ModelState[((MemberExpression)expression.Body).Member.Name] != null)
    {   
        foreach (var erros in helper.ViewData.ModelState[((MemberExpression)expression.Body).Member.Name].Errors)
        {
            Validacao = Validacao + " *";
        }
    }            
    return MvcHtmlString.Create(Validacao);
}

tks

【问题讨论】:

    标签: c# validation custom-attributes


    【解决方案1】:

    任何验证属性都具有ErrorMessage 属性,您可以使用该属性直接在属性中指定错误消息。示例:

    [Required(ErrorMessage = "required error")]
    [MaxLength(10, ErrorMessage = "max length error")]
    

    【讨论】:

    • 这个没有属性?已经想出了这个解决方案,但我认为 exisita 是针对它的。 tks
    • 您可以尝试创建类似于您开始使用的内容,或者尝试编写一些自定义元数据提供程序属性并在渲染时使用它。像这里的东西:dotnetcurry.com/ShowArticle.aspx?ID=687。但我最初提供的解决方案对我来说似乎是最简单的常规项目(如果您有一些特定要求,可能不是)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多