2017-04-11 154 views
2

我有這樣的jQuery函數:阿賈克斯POST請求MVC

function EditContactPost() 
    { 
     var urlEditPost = $("#hdnInfo").data("url_add_contact"); 
     var test = $("#formEditContact").serialize();   
     alert(test); 
     $.ajax({ 
      type: 'post', 
      url: urlEditPost,      
      data:{ marketingContactVM: test },       
     }) 
    } 

我做一個警告,你看,我看,測試變量的所有值正確序列化的形式。但是,當控制器操作在服務器端收到此請求時marketingContactVM始終爲空。這是爲什麼發生? 我控制器操作是這樣的:

[HttpPost] 
     public ActionResult AddContact(MarketingVM marketingContactVM) //always null 
     { 
some code... 
     } 

以防萬一,這是我的模型類,它裏面包含另一個列表:

 public class MarketingVM 
     { 
      public IEnumerable<string> States { get; set; } 
      public List<MarketingVM> MarketingList { get; set; }   
      public string Firstname { get; set; } 
      public string Lastname { get; set; } 
      public string Company { get; set; } 
      public string Address { get; set; } 
      public string City { get; set; } 
      public string State { get; set; } 
      public string Zip { get; set; } 
      public string Country { get; set; } 
      public string Phone { get; set; } 
      public string Fax { get; set; } 
      public string Mail{ get; set; } 
      public string URL { get; set; } 
      public bool IsTrue{ get; set; } 
      public int OtherId{ get; set; } 
    } 

我檢查網絡選項卡中DevTools,這是Request URL:http://localhost:56602/ControllerName/AddContact,應該沒問題。 但數據被髮送爲FormData,就像這樣:

marketingContactVM:Company=Microsoft+Company&Email=user10%40email.co&First= 
Auto&Last=Mapper&Phone=98797988997&Fax=&URL=ww.auto.org&Adress=automapper+ 
street&City=auto+city&State=FL&Zip=33654&Country=USA&MarketingContacts%5B0%5D 
.Name=1%2F03%2F2012+1%3A15+PM&MarketingContacts%5B0%5D.IsSelected=false 

..和這樣。也許正在發送數據的方式。我認爲,正確的格式應該是:

marketingContactVM: Company=Microsoft Company [email protected] First=Charles Last=Johnston Phone=98797988997 Fax=989898 URL=ww.auto.org Adress=North streetCity=Sacramento State=FL Zip=33654 Country=USA MarketingContacts.Name=Piotr MarketingContacts.IsSelected=false

回答

2

因爲你是serializing你不表單需要將其添加在json對象

data:{ marketingContactVM: test }, 

,而不是僅僅通過序列化對象這樣

$.ajax({ 
      type: 'post', 
      url: urlEditPost,      
      data:test,       
     }) 
0

試試這個:

$.ajax({ 
    url: urlEditPost, 
    method: "POST", 
    data: { marketingContactVM: test }, 
    dataType: "json" 
}); 
+0

還是空的對象 – AlexGH

+1

如果可能的話,請把你的網絡調用顯示來自devTools的請求有效載荷和請求URL – Knitesh

0

添加contentType財產。這樣AP.NET MVC就會知道將請求主體反序列化爲JSON。您也可以使用data: JSON.stringify(test)