Support for nested model and class validation with ASP.NET MVC 2.0

巧了我就是萌 提交于 2019-12-07 02:15:00

问题


I'm trying to validate a model containing other objects with validation rules using the System.ComponentModel.DataAnnotations attributes was hoping the default MVC implementation would suffice:

var obj = js.Deserialize(json, objectInfo.ObjectType);
if(!TryValidateModel(obj))
{
    // Handle failed model validation.
}

The object is composed of primitive types but also contains other classes which also use DataAnnotications. Like so:

public class Entry
{
    [Required]
    public Person Subscriber { get; set; }

    [Required]
    public String Company { get; set; }
}

public class Person
{
    public String FirstName { get; set;}

    [Required]
    public String Surname { get; set; }
}

The problem is that the ASP.NET MVC validation only goes down 1 level and only evaluates the properties of the top level class, as can be read on digitallycreated.net/Blog/54/deep-inside-asp.net-mvc-2-model-metadata-and-validation.

Does anyone know an elegant solution to this? I've tried xVal, but they seem to use a non-recursive pattern (http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/).

Someone must have run into this problem before right? Nesting objects in your model doesn't seem so weird if you're designing a web service.


回答1:


I suggest looking into Fluent Validation from codeplex. The validation rules are contained in a separate class (similar to the way NHibernate and Fluent NHibernate work). One uses a lambda to specify the property to validate, supporting child properties.

`

public class MaintainCompanyViewModelValidator : AbstractValidator<MaintainCompanyViewModel>
    {
        public MaintainCompanyViewModelValidator()
        {
            RuleFor(model => model.Company.ShortName)
                .NotEmpty();
        }

`



来源:https://stackoverflow.com/questions/3006516/support-for-nested-model-and-class-validation-with-asp-net-mvc-2-0

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