.NET MVC3条件来验证属性依赖于父对象属性 [英] .net MVC3 conditionally validating property which relies on parent object property

查看:116
本文介绍了.NET MVC3条件来验证属性依赖于父对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下视图模型:

public class StayDetails
{
    public int NumberOfRooms { get; set; }
    public IList<RoomDetail> Rooms { get;set; }
}

public class RoomDetail
{
    public int RoomNumber { get; set; }

    [MinIfRoomRequired("StayDetails.NumberOfRooms", "RoomNumber", 1]
    public int NumberOfAdults { get;set; }
}

我所要做的是创建一个自定义的验证器将验证成年人在房间的数量,并确保至少有1,但前提是需要对当前房间。这可以通过查看StayDetails对象上的NumberOfRooms属性已知

What I am trying to do is create a custom validator which will validate the number of adults in a room and make sure that there is at least 1, but only if the current room is required. This is known by looking at the NumberOfRooms property on the StayDetails object.


我自定义的验证至今:


My custom validator so far:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    // get a reference to the depended properties
    var containerType = validationContext.ObjectInstance.GetType();
    var requiredRoomsField = containerType.GetProperty(RequiredRoomsPropertyName);
    var roomNumberField = containerType.GetProperty(RoomNumberPropertyName);

    if (requiredRoomsField != null && roomNumberField != null)
    {
        // get the value of the dependent properties
        var requiredRoomsValue = requiredRoomsField.GetValue(validationContext.ObjectInstance, null);
        var roomNumberValue = roomNumberField.GetValue(validationContext.ObjectInstance, null);

        ... (remaining logic to test values) ...

我的问题是,我不能访问NumberOfRooms属性时,validationContext.ObjectInstance没有任何refernece的父对象。我想增加一个参考StayDetails对象到对象initialzation在RoomDetails对象,所以我可以从那里引用的财产,但模型绑定不会允许作为RoomDetail对象没有参数的构造函数。

The problem I have is that I cannot access the NumberOfRooms property, the validationContext.ObjectInstance does not have any refernece to the parent object. I thought about adding a reference to the StayDetails object onto the RoomDetails object during object initialzation so I can reference the property from there but model binding wont allow that as the RoomDetail object does not have a parameterless constructor.

有什么建议?

非常感谢,
大卫

Many thanks,
David

推荐答案

您应该定义在 StayDetails类而不是RoomDetail的验证注解。这样,您将拥有所有的值,NumberOfRooms,房间列表和它们各自的RoomNumber和NumberOfAdults。相应地更改您的验证。

You should define validation annotation on StayDetails class instead of RoomDetail. This way you will have all the values, NumberOfRooms, list of rooms and their respective RoomNumber and NumberOfAdults. Change your validator accordingly.

这篇关于.NET MVC3条件来验证属性依赖于父对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆