1

我有以下验证属性:

public class AtLeastOneAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        bool retval = false;
        if (((IEnumerable<object>)value).Count() > 0)
        {
            retval = true;
        }
        return retval;
    }
}

我的自定义模型活页夹:

public class CartOrderBinder : IModelBinder
{
private const string sessionKey = "CartOrder";

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    CartOrder model = null;
    if (controllerContext.HttpContext.Session[sessionKey] != null)
    {
        model = (CartOrder)controllerContext.HttpContext.Session[sessionKey];
    }
    if (model == null)
    {
        model = new CartOrder();
        if (controllerContext.HttpContext.Session != null)
        {
            controllerContext.HttpContext.Session[sessionKey] = model;
        }
    }
    return model;
}

}

这就是我在模型属性上应用属性的方式:

[AtLeastOne]
public List<CartProduct> Products = new List<CartProduct>();

问题是这种验证不起作用。如果我的购物车列表中没有产品,它仍然返回 true。

为什么会这样?

4

1 回答 1

1

我发现了问题。MVC 不想将其public List<CartProduct> Products = new List<CartProduct>();视为属性。因此,我必须将其更改为public List<CartProduct> Products {get;set;}并在我的模型绑定器中为我的产品存储库创建一个实例。

但是,有什么办法可以避免这个问题并仍然使用public List<CartProduct> Products = new List<CartProduct>();?在我的模型中创建实例会非常有用。

于 2014-03-16T09:13:35.107 回答