2012-04-19 16 views
1

我提出這個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/

但是我的情況比這還要簡單,我只是想deseralize和對象,其中包含描述字段,其中一些可能是空白的字符串。

我需要告訴空白字符串和空值之間的差異,以便我可以拋出一個異常,如果我得到任何空值(我的客戶端js代碼不會與c#對象同步,當這種情況發生時,我想知道關於它)。

任何MVC專家誰可以爲我闡明這一點?

謝謝!

回答

3

我認爲問題是,對於ModelBinder的默認行爲是空字段轉換爲類型的模型(MyClass的)的默認值,以便在這些領域的發送一個空字符串將轉化爲

... = default(string); 

這會給你null。

要改變這種行爲,我認爲你需要創建自己的ModelBinder的那個類,並設置這些字段爲空,如果他們來的請求,但它們是空