2012-04-02 67 views
0

如果我理解在asp.net mvc 3中發佈的JSon數據綁定到一個動作的參數,我沒有什麼特別的要做。JSon對象參數成員allways null/empty

例如:

[HttpPost] 
public JsonResult Synchro(TestJSON data) 
{ 
    ... data member should contain the JSon data sent... 
    return Json("ok"); 
} 

的TestJSON類:

public class TestJSON 
{ 
    public string chaine; 
    public int nombre; 
} 

和JSON數據:

{chaine:"Test",nombre:"23"} 

(與curl.exe用於測試發送)但是數據成員全是nu在Syncho功能中爲ll或0。

我搜查了很多,我無法理解。

我發現了一些奇怪的東西。如果我刪除JsonValueProviderFactory(在的Application_Start):

var v = ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().First(); 
ValueProviderFactories.Factories.Remove(v); 

,如果我創造我自己的模型粘合劑(某處發現對賭):

public class JeanJsonModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) 
     { 
      // not JSON request 
      return null; 
     } 

     var request = controllerContext.HttpContext.Request; 
     var incomingData = new StreamReader(request.InputStream).ReadToEnd(); 

     if (String.IsNullOrEmpty(incomingData)) 
     { 
      // no JSON data 
      return null; 
     } 

     JavaScriptSerializer serializer = new JavaScriptSerializer(); 
     return serializer.Deserialize(incomingData, bindingContext.ModelType); 
    } 
    } 

,如果我手動綁定我的參數:

[HttpPost] 
public JsonResult Synchro([ModelBinder(typeof(JeanJsonModelBinder))] TestJSON data) 
{ 
    ... data member should contains JSon data sent... 
    return Json("ok"); 
} 

它的工作原理!

有什麼想法?

感謝

回答

2

嘗試使用屬性模型類,而不是數據成員。 我認爲如果你用你的默認模型綁定器替換它可能會工作,但你仍然應該使用propertys,因爲這是標準模式。

+0

你是對的!我覺得有點愚蠢,我花了幾個小時不了了之。非常感謝你 ! – Factorial 2012-04-02 15:53:11

+0

很好,不覺得愚蠢,每次失敗都是一次學習的機會,越是失敗越好,至少在理論上......請隨時通過點擊我帖子旁邊的按鈕來回答你的問題。 ) – 2012-04-02 15:59:28