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

問題が見つかりました。public List<CartProduct> Products = new List<CartProduct>();MVC は、プロパティとして表示したくありません。そのため、これを変更しpublic List<CartProduct> Products {get;set;}て、モデル バインダーに製品リポジトリのインスタンスを作成する必要がありました。

それでも、この問題を回避して引き続き使用できる方法はありますpublic List<CartProduct> Products = new List<CartProduct>();か? 私のモデルでインスタンスを作成すると非常に便利です。

于 2014-03-16T09:13:35.107 に答える