C# MVC 3将jquery$.ajax请求json反序列化为对象填充空字符串而不是空字符串
我正在打这个ajax电话:C# MVC 3将jquery$.ajax请求json反序列化为对象填充空字符串而不是空字符串,c#,javascript,jquery,asp.net-mvc-3,C#,Javascript,Jquery,Asp.net Mvc 3,我正在打这个ajax电话: $.ajax({ url: "/test/whatever", type: 'post', contentType: 'application/json' data: {"fieldone":'test',"fieldtwo":'',"fieldthree":null,"fieldfour":'test'} }); 在控制器中,我有: [HttpPost] public s
$.ajax({
url: "/test/whatever",
type: 'post',
contentType: 'application/json'
data: {"fieldone":'test',"fieldtwo":'',"fieldthree":null,"fieldfour":'test'}
});
在控制器中,我有:
[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
}
那么,有人知道为什么在这种情况下空白字符串会变成空字符串吗?
我发现了这篇文章,它讨论了javascriptserializer中可空属性的一个bug:
但我的情况甚至更简单,我只想反序列化包含描述性字段的对象,其中一些字段可能是空白字符串
我需要区分空字符串和空字符串,以便在得到空字符串时抛出异常(发生这种情况时,我的客户端js代码通常与c对象不同步,我想知道这一点)
有没有MVC专家能帮我解释一下
谢谢 我认为问题在于ModelBinder的默认行为是将空字段转换为模型中类型(MyClass)的默认值,因此在这些字段中发送空字符串将转换为
... = default(string);
这会给你零
要改变这种行为,我认为您需要为该类创建您自己的ModelBinder,并将这些字段设置为空字符串(如果它们在请求中出现但为空)