asp.net mvc - ModelState.IsValid is false when I have a nullable parameter -
i reproduced issue having in brand new mvc web api project.
this default code slight modification.
public string get(int? id, int? = null) { var isvalid = modelstate.isvalid; return "value"; }
if go http://localhost/api/values/5?something=123
works fine, , isvalid true
.
if go http://localhost/api/values/5?something=
isvalid false
.
the issue having if provide null or omitted value item nullable, modelstate.isvalid flags validation error saying "a value required not present in request."
the modelstate dictionary looks this:
with 2 entries something
, 1 nullable, not sure if significant or not.
any idea how can fix model valid when nullable parameters omitted or provided null? using model validation within web api , breaks if every method nullable parameter generates model errors.
it appears default binding model doesn't understand nullable types. seen in question, gives 3 parameter errors rather expected two.
you can around custom nullable model binder:
model binder
public class nullableintmodelbinder : imodelbinder { public bool bindmodel(system.web.http.controllers.httpactioncontext actioncontext, modelbindingcontext bindingcontext) { if (bindingcontext.modeltype != typeof(int?)) { return false; } valueproviderresult val = bindingcontext.valueprovider.getvalue(bindingcontext.modelname); if (val == null) { return false; } string rawvalue = val.rawvalue string; // not supplied : /test/5 if (rawvalue == null) { bindingcontext.model = null; return true; } // provided no value : /test/5?something= if (rawvalue == string.empty) { bindingcontext.model = null; return true; } // provided value : /test/5?something=1 int result; if (int.tryparse(rawvalue, out result)) { bindingcontext.model = result; return true; } bindingcontext.modelstate.addmodelerror(bindingcontext.modelname, "cannot convert value int"); return false; } }
usage
public modelstatedictionary get( int? id, [modelbinder(typeof(nullableintmodelbinder))]int? = null) { var isvalid = modelstate.isvalid; return modelstate; }
adapted asp.net page: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api further reading , alternative method set @ class(controller) level rather per parameter.
this handles 3 valid scenarios:
/test/5 /test/5?something= /test/5?something=2
this first give "something" null. else (eg ?something=x
) gives error.
if change signature to
int? somthing
(ie remove = null
) must explicitly provide parameter, ie /test/5
not valid route unless tweak routes well.
Comments
Post a Comment