pilavdzice
pilavdzice

Reputation: 958

MVC 3 deserialization of jquery $.ajax request json into object populates nulls instead of blank strings

I am making this ajax call:

   $.ajax({
        url: "/test/whatever",
        type: 'post',
        contentType: 'application/json'
        data: {"fieldone":'test',"fieldtwo":'',"fieldthree":null,"fieldfour":'test'}
    });

in the controller I have:

    [HttpPost]
    public string Whatever(MyModel object)
    {
        //fieldone, fieldtwo and fieldthree are all type string  
        //at this point:
        // object.fieldone contains the string 'test'
        // object.fieldtwo is NULL, but WHY?! and how can I have it correctly deserialize to blank string
        // object.fieldthree is correctly null, which is fine
        // I have no fieldfour in my object, so it is ignored, that makes sense.
        // object.newfield is correctly null, because I didn't pass a value for it in my JS
    }

So, does anyone know why blank strings are turning into nulls in this case? I found this post which talks about a bug in javascriptserializer for nullable properties:

http://juristr.com/blog/2012/02/aspnet-mvc3-doesnt-deserialize-nullable/

But my case is even simpler than that, I just want to deseralize and object that contains descriptive fields, some of which might be blank strings.

I need to tell the difference between blank strings and nulls so that I can throw an exception if I get any nulls (my client js code isn't in sync with the c# object ususally when this happens and I want to know about it).

Any MVC experts out there who can shed light on this for me?

Thanks!

Upvotes: 1

Views: 951

Answers (1)

Jaime
Jaime

Reputation: 6814

I think the problem is that the default behavior for the ModelBinder is to convert empty fields to the default value of the type in your model (MyClass) so sending an empty string in those field would translate to

 ... = default(string); 

which would give you null.

To change this behavior I think you need to create your own ModelBinder for that class and set those fields to empty string if they come in the request but they are empty

Upvotes: 3

Related Questions