ASP.NET MVC接收“null”作为字符串而不是null

时间:2011-12-09 15:58:59

标签: javascript jquery ajax asp.net-mvc

我对json或ASP.NET MVC有问题,我使用的是ASP.NET MVC,这是我从客户端发送的内容。

注意 在Chrome中调试后,我解释说这是在javascript中传递的内容,我不是手动将State设置为null,因为它从其他地方作为null返回。这再一次不在我的掌控之中,因为它来自数据库。

调试时,State显示它为null,而不是“null”,但在MVC中调试时显示“null”而不是null。

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

我的ASP.NET MVC处理程序收到......

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

enter image description here

是ASP.NET MVC还是jQuery的问题?

因此,jQuery将null作为“null”发送,还是将null设置为“null”的MVC?

我不得不递归地创建新的对象层次结构(克隆对象)并将其发送到jQuery,因为jQuery将数据发送为Form Encoded,其中无法表示null,但理想情况下jQuery不应该序列化为null所有

3 个答案:

答案 0 :(得分:6)

请勿发送字段:

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

<小时/> 在重新阅读您的帖子

之后进行修改
var data = {
                 Country: 'US',
                 State: null
             }
if (!data.State) delete data.State;
$.ajax('/Client/Post',
    {
       method: 'POST',
       data: data
    }
});

这与上述FYI

的原理完全相同

答案 1 :(得分:3)

jQuery这样做。您可以通过firebug fiddler,chrome dev helper等监视请求。

在这种情况下,也许您可​​以使用空字符串而不是null

data: {
    Country: 'US',
    State: ""
}

答案 2 :(得分:3)

如果您必须发布数据而不是使用对象作为jSoN,请参阅链接

To pass whole JSON objects into controller of MVC

相关问题