我的 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...
}
}
是 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/