ASPNET MVC - Why is ModelState.IsValid false “The x field is required” when that field does have a value?

后端 未结 3 1990
孤城傲影
孤城傲影 2021-01-12 06:45

I have a model like this:

public PurchaseOrder 
{
    [Required] [StringLength(15)]
    public virtual string OrderNumber {get;set;}
    // etc.        
}
         


        
3条回答
  •  盖世英雄少女心
    2021-01-12 07:11

    Well I have "solved" it, but I do not really understand why the changes I made have helped.

    I had to do three things:

    1. Remove the json filter (filters don't bind)

    2. Change the contentType to application/json

      $.ajaxSetup({ contentType: "application/json; charset=utf-8" });

    3. Use the MVC futures download Microsoft.Mvc.dll as described here: http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx. Where is says to add this to Application_Start() in Global.asax.cs:

      ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

    Now I dont know exactly why that has worked, but it has.

    Unfortunately it has had a negative side effect: the contenttype is applied to all $.get() and $.post() methods, and broken all my jqgrids - they only seem to work if the content type is the default of application/x-www-form-urlencoded

    So I've asked 2 follow on questions:

    1. Is it possible to set the content type in a $.post() call? Then I wouldn't need to set it globally Jquery - How to make $.post() use contentType=application/json?

    2. Is it possible to make jqrid work if the contenttype is application/json? Jquery - How to make $.post() use contentType=application/json?

提交回复
热议问题