Note that there are some explanatory texts on larger screens.

plurals
  1. POASPNET MVC - Why is ModelState.IsValid false "The x field is required" when that field does have a value?
    text
    copied!<p>I have a model like this:</p> <pre><code>public PurchaseOrder { [Required] [StringLength(15)] public virtual string OrderNumber {get;set;} // etc. } </code></pre> <p>When I submit an order from the view (using $.post, not input type=submit) it goes to my controller class:</p> <pre><code>public class PurchaseOrderController { public JsonResult Save(PurchaseOrder order) { // TryUpdateModel(order); // commented out since modelstate.isvalid remains false anyway if (ModelState.IsValid) { // its never valid } } } </code></pre> <p>ModelState.IsValid always returns false, with the error: "The Order Number field is required." But there is a value in this field (?? why) </p> <p>Why would it say "value is required" when it does have a value? Have I missed something? Is it because of the $.post instead of the submit? What can I do?</p> <p>This is what the debugger looks like:</p> <p><a href="http://www.freeimagehosting.net/uploads/f734f3d95d.png" rel="nofollow noreferrer">alt text http://www.freeimagehosting.net/uploads/f734f3d95d.png</a></p> <p><strong>EDIT: Extra info....</strong></p> <p>I really think that for some reason the model binding is not happening. When I try this code found here: )</p> <pre><code>if (!ModelState.IsValid) { ModelState.Clear(); ModelMetadata modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() =&gt; order, order.GetType()); ModelValidator compositeValidator = ModelValidator.GetModelValidator(modelMetadata, base.ControllerContext); foreach (ModelValidationResult result in compositeValidator.Validate(null)) { this.ModelState.AddModelError(result.MemberName, result.Message); } } </code></pre> <p>Then ModelState.IsValid = true. compositeValidator.Validate() returns 0 errors. I think this indicates the model was not bound, but I still don't know why.</p> <p>The controller method actually looks like this (I missed out the filter when originally writing this question)</p> <pre><code>[JsonFilter(Param = "order", JsonDataType = typeof(PurchaseOrder))] public JsonResult Save(PurchaseOrder order) { // etc ... } </code></pre> <p>And the JsonFilter does this to extract the POCO from the json submitted data:</p> <pre><code>filterContext.ActionParameters[Param] = jsSerializer.Deserialize(inputContent, JsonDataType); </code></pre> <p>I put a breakpoint on this line, and order is valid, plus order.OrderNumber has the correct value.</p> <p>So still unresolved, but hopefully this extra info will help with finding a solution </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload