Attaching validation to EF objects used in MVC controllers/views?

前端 未结 3 1213
青春惊慌失措
青春惊慌失措 2021-01-21 04:26

We\'re throwing together a quick project (CRUD forms) and decided to skip view models and use EF entities directly in controllers and views. Since I\'m not used to this approach

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-21 04:58

    You need to use a partial 'buddy' meta class and decorate it with validation attributes.

    For example, say your entity was 'Foo':

    [MetadataType(typeof(FooMetadata))]
    public partial class Foo {}
    
    public class FooMetadata
    {
        //apply validation attributes to properties
        [Required]
        [Range(0, 25)]
        [DisplayName("Some Neato Property")]
        public int SomeProperty { get; set; }
    }
    

    For more information see this link on MSDN:

    Customize Data Field Validation in the Model

    Cheers.

提交回复
热议问题