开发者

What are the benefits of using Data Annotation over a service layer in ASP.NET validation?

开发者 https://www.devze.com 2023-02-10 09:34 出处:网络
I\'m looking at adding validation into my web app.Some models\' validity depends on the state of other models in the app.

I'm looking at adding validation into my web app. Some models' validity depends on the state of other models in the app.

What are the开发者_如何学Python benefits of using the data annotation framework over a service layer? It seems to me that the service implementation would be easier, however I understand the benefits of having validation close to the data.

Thanks!


MVC 3 / MVC 2 with .NET 4.0

Sounds like you want to use IValidatableObject, Scott Gu wrote a blog post about this.

What I normaly do if I have an Entity Framework model and I want to add custom validation to my object I do a partial class like this:

public partial class MyObjectModel : IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (someNumberProperty > anotherNumberProperty) 
            yield return new ValidationResult(
                    "someNumber property is larger than anotherNumberProperty", 
                                              new[] { "someNumberProperty" });
        if (someNumberProperty == 0) 
            yield return new ValidationResult("someNumber property cannot be 0", 
                                                new[] { "someNumberProperty" });

    }
}

MVC 2

Here is a another post by Scott Gu on how to acheive model validation but you might want to look in to Custom Validation.

0

精彩评论

暂无评论...
验证码 换一张
取 消