ASP.NET MVC复杂模型验证

时间:2010-10-27 18:07:05

标签: c# asp.net-mvc validation model

我有一个复杂的模型

public class ComplexModel
{

    public UserModel userModel;

    public ExtraInfoModel extraModel;
}

,其中

UserModel可能包含必填字段

如:

public class UserModel
{

     [Required]
     public string email;
}

如何验证ComplexModel以确保其成员模型上的数据注释被用于ComplexModel验证中的帐户?

谢谢。

更新:

这是我的确切方案。当我在ManageProfileModel上的控制器操作中调用ModelState.IsValid时,无论是否设置了GeneralInfoModel的ListModelRequired成员的“SelectedValue”,模型状态都是有效的。

public class ManageProfileModel
{
    [Required(ErrorMessage="Experience is required")]
    public int LevelOfExperienceTypeID { get; set; }
    public GeneralInfoModel GeneralInfoModel { get; set; }
}

public class GeneralInfoModel
{
    [Required]
    [DisplayName("Profile Headline")]
    public string ProfileName { get; set; }

    [DisplayName("Signature")]
    public string Signature { get; set; }

    [Required]
    public ListModelRequired LevelOfExperience { get; set; }
}

public class ListModel
{
    public ListModel()
    {
    }

    public ListModel(string name)
    {
        this.Name = name;
    }

    public ListModel(string name, string selectedValue):this(name)
    {
        this.SelectedValue = selectedValue;
    }

    public ListModel(string name, IEnumerable<SelectListItem> members):this(name)
    {
        this.Members = members;
    }

    public ListModel(string name, IEnumerable<SelectListItem> members, string selectedValue)
        : this(name, members)
    {
        this.SelectedValue = selectedValue;
    }

    public IEnumerable<SelectListItem> Members { get; set; }

    public string Name { get; set; }

    public virtual string SelectedValue { get; set; }

    public string Label { get; set; }
}

public class ListModelRequired : ListModel
{
    [Required]
    public override string SelectedValue { get; set; }

    public ListModelRequired():base()
    {
    }

    public ListModelRequired(string name):base(name)
    {
    }

    public ListModelRequired(string name, string selectedValue):base(name,selectedValue)
    {
    }

    public ListModelRequired(string name, IEnumerable<SelectListItem> members)
        : base(name, members)
    {
    }

    public ListModelRequired(string name, IEnumerable<SelectListItem> members, string selectedValue)
        : base(name, members,selectedValue)
    {
    }
}

1 个答案:

答案 0 :(得分:0)

我认为默认的模型绑定器是正确的,验证使用数据注释的子模型。你实际上有什么问题吗?例如,我有类似的东西:

public class OnlineDonationModel
{
     [Required]
     public decimal? Amount { get; set; }

     public ContactModel Contact { get; set; }
}

public class ContactModel
{
     [Required]
     public string FirstName { get; set; }

     [Required]
     public string LastName { get; set; }

     [Required]
     public string Address { get; set; }

     ...
}