繁体   English   中英

ASP.NET MVC5创建自定义验证属性不起作用

[英]ASP.NET MVC5 creating custom validation attribute is not working

我具有以下验证属性:

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。

为什么会这样呢?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM