ASP.NET MVC 3 ModelState.IsValid is always returning true for JSON encoded data using Ext.Direct

2.2k Views Asked by At

I have a form and the only item that is required is the customer name. So in my model, I have:

 [DisplayName("Customer name*:")]
 [Required]
 public string CustomerName
 { get; set; }

Previously, I was doing an HTML post and everything worked fine including validation.

Now, I've "ajaxified" the form, using Ext.direct.mvc (http://code.google.com/p/ext-direct-mvc/), which is a significant fact, and posting the data in Json format and the data is getting posted successfully.

enter image description here

When I put a breakpoint in my code (currently modified for debugging purposes):

 [DirectInclude]
    [HttpPost]
    public ActionResult SaveOrUpdateOrderLines(CustomerOrderModel customerOrderModel)
    {

        if (!ModelState.IsValid)
        {
            return ModelState.JsonValidation();
        }

        return null;

I see that the CustomerOrderModel.CustomerOrderHeader.CustomerName = ""

enter image description here

But the ModelState.IsValid is true.

enter image description here

Now for some of the things I've tried:

  1. I have inserted the following code, just before checking for ModelState.isValid, in order to ensure that CustomerName = null

    customerOrderModel.CustomerOrderHeader.CustomerName = null;

  2. I have tried using TryUpdateModel(customerOrderModel) but I get the following error message:

    TryUpdateModel threw an exception of type 'System.MissingMethodException'

  3. I've tried modifying the json data so that the "root" "CustomerOrderHeader" was renamed to "customerOrderModel" to match the parameter.

None of these things worked. So what could I be doing wrong that validation isn't working anymore? What steps can I take to debug the issue?

EDIT for counsellorBen

enter image description here

EDIT 2 for counsellorben

enter image description here

1

There are 1 best solutions below

7
On

The problem is that when trying to bind a Json response, the name of the variable in your controller action must match the name of the variable passed on the client side. Your model is valid, because CustomerOrderHeader is null.

In your client script, you should wrap your entire model in an element named "customerOrderModel", so the name matches the variable name in your action.