简体   繁体   中英

ASP.NET MVC5 creating custom validation attribute is not working

I have the following validation attribute:

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

My custom model binder:

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;
}

}

This is how I applied the attribute on my model's property:

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

The problem is that this validation is not working. If I don't have a product in my cart list it still returns true.

Why is this happening?

I found the problem. The MVC doesn't want to see public List<CartProduct> Products = new List<CartProduct>(); as a property. So I had to change this into public List<CartProduct> Products {get;set;} and create an instance of for my products repository in my model binder.

But still, is there any way I can avoid this problem and still use the public List<CartProduct> Products = new List<CartProduct>(); ? It would be very useful to create the instance in my model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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