MVC 3反序列化jquery $ .ajax请求json到对象填充空值而不是空字符串

时间:2012-04-19 21:59:33

标签: 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 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
    }

那么,有没有人知道为什么空字符串在这种情况下变成空值? 我发现这篇文章讨论了jlableserializer中可为空的属性的错误:

http://juristr.com/blog/2012/02/aspnet-mvc3-doesnt-deserialize-nullable/

但是我的情况甚至比这更简单,我只想对包含描述性字段的deseralize和object进行解析,其中一些可能是空字符串。

我需要告诉空字符串和空值之间的区别,这样我就可以抛出异常,如果我得到任何空值(我的客户端js代码通常不会与c#对象同步,当发生这种情况时我想了解一下它)。

那里有哪些MVC专家可以为我揭示这一点?

谢谢!

1 个答案:

答案 0 :(得分:3)

我认为问题在于ModelBinder的默认行为是将空字段转换为模型中类型的默认值(MyClass),因此在这些字段中发送空字符串将转换为

 ... = default(string); 

会给你null。

要更改此行为,我认为您需要为该类创建自己的ModelBinder,并将这些字段设置为空字符串,如果它们在请求中但是它们是空的