How to validate my model in a custom model binder?

前端 未结 3 950
有刺的猬
有刺的猬 2020-12-31 05:44

I asked about an issue I have with comma delimited numeric values here.

Given some of the replies, I attempted to try to implement my own model binder as follows:

3条回答
  •  醉酒成梦
    2020-12-31 06:28

    I got your validation to work fine by changing when BindModel fires. In your code, you have these lines in PropertyModelBinder:

    object o = base.BindModel(controllerContext, newBindingContext);
    newBindingContext.ModelState.Remove("Price");
    newBindingContext.ModelState.Add("Price", new ModelState());
    newBindingContext.ModelState.SetModelValue("Price", new ValueProviderResult(price, price, null));
    return o;
    

    I moved base.BindModel to fire immediately before returning the object (after reconstructing context) and now validation works as expected. Here is the new code:

    newBindingContext.ModelState.Remove("Price");
    newBindingContext.ModelState.Add("Price", new ModelState());
    newBindingContext.ModelState.SetModelValue("Price", new ValueProviderResult(price, price, null));
    object o = base.BindModel(controllerContext, newBindingContext);
    return o;
    

提交回复
热议问题