【问题标题】:MVC 3 deserialization of jquery $.ajax request json into object populates nulls instead of blank stringsMVC 3 将 jquery $.ajax 请求 json 反序列化为对象填充空值而不是空白字符串
【发布时间】:2012-04-19 21:59:32
【问题描述】:

我正在做这个 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 专家可以为我阐明这一点吗?

谢谢!

【问题讨论】:

    标签: c# javascript jquery asp.net-mvc-3


    【解决方案1】:

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

     ... = default(string); 
    

    这会给你null。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-16
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 2022-07-08
      相关资源
      最近更新 更多