javascript - ASP.NET MVC 接收 "null"作为字符串而不是 null

标签 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”还是 MVC 将 null 设置为“null”?

解决方案

我不得不递归地创建新的对象层次结构(克隆对象)并将其发送给 jQuery,因为 jQuery 将数据作为表单编码发送,其中无法表示 null,但理想情况下 jQuery 不应在以下位置序列化 null全部。

最佳答案

不发送字段:

$.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 完全相同

关于javascript - ASP.NET MVC 接收 "null"作为字符串而不是 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448150/

相关文章:

javascript - Jquery 加载更多有关滚动速度的信息

php - 单击 Facebook Like 按钮后运行 PHP 查询的 Ajax 代码

javascript - Babel 在特定场景下为变量加下划线前缀

javascript - 为什么我不能 JSON.stringify localStorage

javascript - 使用 Greasemonkey 修改所有链接

javascript - 如何将 JQuery 效果限制为嵌套 block 中的一个元素

javascript - jQuery 与 ExtJS 兼容吗?

javascript - 将 jquery 变量传递给另一个函数

ajax - 如何测试 React/Flux 组件状态?

javascript - jQuery AJAX : Get Meta-Data from Cross Domain HTML-Page