Adding DataAnnontations to Generated Partial Classes

倖福魔咒の 提交于 2019-11-28 07:04:21

What you will need to do is create a 'buddy class' and apply the Data Annotations to that class:

[MetadataType(typeof(UserValidation))]
public partial class User 
{
  ...
}

public class UserValidation
{
  [DataType(DataType.EmailAddress, ErrorMessage = "Please enter an email address")]
  public string Email { get; set; }
}

You should create a buddy class as explained here by Scott Guthrie http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

This won't directly answer your question, but I had the same problem, and rather than using DataAnnotations, I've been using the FluentValidation framework {0} with great success so far. It works nicely because it provides much of the same functionality, but doesn't apply validation by using attributes on members of the class. Validation happens in a completely separate class that acts on the class being validated (i.e. UserValidator).

{0}: http://fluentvalidation.codeplex.com/

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