问题
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