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

MVC 3 deserialization of jquery $.ajax request json into object populates nulls instead of blank strings

本文关键字:空值 填充 字符串 空白 对象 ajax MVC json 请求 反序列化 jquery      更新时间:2023-09-26

我正在做这个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-不反序列化-空/

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

我需要分辨空白字符串和空值之间的区别,以便在获得任何空值时可以抛出异常(发生这种情况时,我的客户端 js 代码通常与 c# 对象不同步,我想知道它)。

有MVC专家可以为我阐明这一点吗?

谢谢!

我认为

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

 ... = default(string); 

这会给你空。

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