我正在做这个 ajax 调用:
$.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 中的一个错误:
http://juristr.com/blog/2012/02/aspnet-mvc3-doesnt-deserialize-nullable/
但我的情况比这更简单,我只想反序列化和包含描述性字段的对象,其中一些可能是空白字符串。
我需要区分空白字符串和空值,以便在我得到任何空值时抛出异常(当这种情况发生时,我的客户端 js 代码通常与 c# 对象不同步,我想知道它)。
那里有任何 MVC 专家可以为我阐明这一点吗?
谢谢!