更改StringLengthAttribute的所有元数据属性错误消息

时间:2015-03-24 07:00:51

标签: asp.net-mvc asp.net-mvc-4

我可以修改modelmetadata的所有属性StringLengthAttribute错误消息吗?我可以通过调用GetValidators()逐个更改。

这是我的htmlhelper代码:

public static HtmlString TestHelper<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> pFieldExpression)
    {
        ModelMetadata fieldmetadata = ModelMetadata.FromLambdaExpression(pFieldExpression, html.ViewData);

        // option 1
        var a = (from s in fieldmetadata.ModelType.GetProperties()
                  select s.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true)
                 );
        foreach (var i in a)
        {
            // ther is no error message
        }


        // option 2
        var validatorsDictionary = ModelValidatorProviders.Providers
                                                     .GetValidators(fieldmetadata, html.ViewContext)
                                                     .SelectMany(v => v.GetClientValidationRules());
        // validatorsDictionary is empty and seems cannot modify metadata

        return new HtmlString("test");
    }

提前致谢

0 个答案:

没有答案