ASP.NET MVC 2 - Property validation

谁说我不能喝 提交于 2019-12-11 18:58:01

问题


I'm new to MVC and have a question regarding validation. Is there a way to dynamically set the Error Message?

For example, how could I achieve the following (ignore the hardcoded 50, this could come from the Web.config or specific to the current logged).

[MetadataType(typeof(DocumentValidation))]
public partial class Document
{
    public class DocumentValidation
    {
        private const int MaxLength = 50;

        [Required(ErrorMessage = "Document Title is required")]
        [StringLength(MaxLength, ErrorMessage = "Must be under " + MaxLength.ToString() + " characters")]
        public string Title { get; set; }
    }

}

Thanks,


回答1:


Check out IDataErrorInfo and this question I asked about IDataErrorInfo vs. DataAnnotations.




回答2:


This should be possible with dynamic attributes but involves some trickery:

Dynamic Attributes in C#




回答3:


Depending how dynamically you're trying to change ErrorMessage. This might be one solution to your problem: haacked.com - Localizing ASP.NET MVC Validation

It's a good guide to get localized error message from the resources.´



来源:https://stackoverflow.com/questions/3500619/asp-net-mvc-2-property-validation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!