Can I define properties in partial classes, then mark them with attributes in another partial class?

前端 未结 5 1189
野趣味
野趣味 2020-12-02 06:17

Is there a way I can have a generated code file like so:

public partial class A {
public string a {get; set;}
}

and then in another file:

5条回答
  •  醉梦人生
    2020-12-02 06:59

    I've seen something like this done in an article by Scott Guthrie (near the end of it) - didn't try it myself, though.
    http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

    [MetadataType(typeof(Person_Validation))]
    public partial class Person
    {
        // Partial class compiled with code produced by VS designer
    }
    
    [Bind(Exclude="ID")]
    public class Person_Validation
    {
        [Required(ErrorMessage = "First Name Required")]
        [StringLength(50, ErrorMessage = "Must be under 50 characters")]
        public string FirstName { get; set; }
    
        [Required(ErrorMessage = "Last Name Required")]
        [StringLength(50, ErrorMessage = "Must be under 50 characters")]
        public string LastName { get; set; }
    
        [Required(ErrorMessage = "Age Required")]
        [Range(0, 120, ErrorMessage = "Age must be between 0 and 120")]
        public int Age { get; set; }
    
        [Required(ErrorMessage = "Email Required")]
        [Email(ErrorMessage = "Not a valid email")]
        public string Email { get; set; }
    }
    

提交回复
热议问题