Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC receives "null" as a string instead of null

I have something wrong with either json or ASP.NET MVC, I am using ASP.NET MVC and here is what I am sending from the client.

NOTE After debugging in Chrome, I am explaining that this is what is passed within javascript, I am not manually setting State to null as it is coming as result from somewhere else as null. Which once again is not in my control as it is coming from database.

While debugging, State displays that it is null, instead of "null", but while debugging in MVC it is displaying "null" instead of null.

$.ajax(
   '/Client/Post',
   {
       method: 'POST',
       data: {
                 Country: 'US',
    // this is null because it is coming from somewhere else as null
                 State: null
             }
   });

My ASP.NET MVC Handler receives...

public ActionResult Post(Client model){
    if(model.State == "null") 
    {
         /// this is true... !!!!
    }
    if(model.State == null )
    {
         // :( this should be true...
    }
}

enter image description here

Is it problem of ASP.NET MVC or jQuery?

So is it jQuery that sends null as "null" or is it MVC that is setting null as "null"?

SOLUTION

I had to just recursively create new object hierarchy (cloning the object) and send it to jQuery, as jQuery sent data as Form Encoded, in which there is no way to represent null, however ideally jQuery should not have serialized null at all.

like image 956
Akash Kava Avatar asked Dec 09 '11 15:12

Akash Kava


3 Answers

Don't send the field:

$.ajax('/Client/Post',
{
   method: 'POST',
   data: {
             Country: 'US'
         }
});


Edit after I re-READ your post
var data = {
                 Country: 'US',
                 State: null
             }
if (!data.State) delete data.State;
$.ajax('/Client/Post',
    {
       method: 'POST',
       data: data
    }
});

This is the same exact principle as above FYI

like image 185
Joe Avatar answered Oct 23 '22 21:10

Joe


jQuery does this. You can monitor the request by firebug fiddler, chrome dev helper, etc.

In this case, maybe you could use empty string instead of null:

data: {
    Country: 'US',
    State: ""
}
like image 22
Jeffrey Zhao Avatar answered Oct 23 '22 19:10

Jeffrey Zhao


if you have to post data than use object as jSoN see the link

To pass whole JSON objects into controller of MVC

like image 3
Dewasish Mitruka Avatar answered Oct 23 '22 21:10

Dewasish Mitruka