2014-10-27 44 views
0

我試圖通過Ajax請求發佈我的表單數據,該數據是通過Ajax請求綁定到控制器的,但是,儘管請求標頭控制器顯示數據爲null顯示數據正在發送。通過Ajax發佈表單數據導致空模型數據

代碼如下。我試過數據:JSON.stringify(表單),它導致一個空模型,而下面的結果是一個空數據模型。

查看

$(document).on('click', '#saveData', function() { 
        if ($('#form').valid()) { 
         var form = $('#form').serialize(); 
         $.ajax(
          { 
           url: '@Url.Action("CreateClient", "Processors")', 
           type: 'POST', 
           cache: false, 
           async: false, 
           dataType: 'json', 
           contentType: 'application/json', 
           data: JSON.stringify(form) 
         }) 
          .success(function (response) 
{ alert(response); }) 
          .error(function (response) 
{ alert(response); }); 
        } 
       }); 

控制器

public ActionResult CreateClient(ModelData form) 
    { 
     if (form == null || !ModelState.IsValid) 
     {     
      return Json("Error"); 
     } 

     return Json("Success"); 

    } 

回答

2

有兩個問題你的方法。

如果你的模型類ModelData例如,

class ModelData { 
    public string Foo {get;set;} 
    public string Bar {get;set;} 
} 

適當的數據發送是{foo:"foo1", bar:"bar1"},或最終{Foo:"foo1", Bar: "bar1"},這取決於你如何配置你的序列化 - 爲您指定的contentType 'application/json'

但是,您正在使用jquery serialize()來閱讀您的表單。此方法返回一個字符串,格式爲"foo=foo1&bar=bar1",適用於contentType'application/x-www-form-urlencoded'。所以你必須以你想要發送數據的格式作出決定。如果要繼續使用serialize()從DOM獲取數據,請改用'application/x-www-form-urlencoded'

其次,JSON。 stringify()將從一個對象創建一個JSON字符串。一個字符串也是一個對象。因此,將字符串傳遞給此函數會將字符串包裝爲一個字符串,這沒有多大意義:數據將類似於"\"foo=foo1&bar=bar1\""。以同樣的方式,當contentType爲'json'時,jQuery ajax函數將期待一個對象作爲它的數據參數,所以如果您之前將對象轉換爲字符串,它將以如下形式發送:字符串。基本上,無論您最終爲您的請求選擇contentType,請不要將JSON.stringify用於您的數據參數。

TL; DR:爲了得到這個工作,使用默認contentType或明確聲明它爲每下面,並通過形式變量 - 是:

var form = $('#form').serialize(); 
$.ajax(
    { 
     //(...) 
     contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
     data: form, 
     //(...)