MVC 3 C#RequiredAttribute扩展

时间:2011-10-26 13:44:44

标签: asp.net-mvc-3

我尝试扩展RequiredAttribute以进行一些本地化。我写了这个:

public class LocalizedRequiredAttribute : RequiredAttribute

{
    public LocalizedRequiredAttribute(string errorMessageResourceName)
    {
        this.ErrorMessageResourceName = string.IsNullOrEmpty(errorMessageResourceName) ? "Required_ValidationError" : errorMessageResourceName;
        ErrorMessageResourceType = typeof(bop.Core.Resources.Label);
    }
}

{ public LocalizedRequiredAttribute(string errorMessageResourceName) { this.ErrorMessageResourceName = string.IsNullOrEmpty(errorMessageResourceName) ? "Required_ValidationError" : errorMessageResourceName; ErrorMessageResourceType = typeof(bop.Core.Resources.Label); } }

在客户端,不会呈现验证消息。怎么了? 感谢帮助。 卢卡

2 个答案:

答案 0 :(得分:4)

在您的后续评论中,您指定了客户端验证无效。看起来你问了同样的问题here,但为了StackOverflow,我会提供答案。

LocalizedRequiredAttribute类还必须实现IClientValidatable才能使客户端验证工作:

using System.Web.Mvc;
public class LocalizedRequiredAttribute : RequiredAttribute, IClientValidatable
{
    // your previous code

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            // format the error message to include the property's display name.
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),

            // uses the required validation type.
            ValidationType = "required"
        };
    }
}

答案 1 :(得分:1)

查看Darin Dimitrov撰写的thisthis帖子。

希望这有帮助。