2014-09-26 50 views
0

我通過JQuery向MVC HttpPost操作方法發送一個值,但是卻獲得一個空值。當我發送一個普通的字符串時,它工作正常,但是當我發送一個數組時,它會得到空值。這是代碼。MVC [HttpPost]方法接收空參數

代碼發送值

function Submit() { 
     var QSTR = { 
      name: "Jhon Smith", 
      Address: "123 main st.", 
      OtherData: [] 
     }; 
     QSTR.OtherData.push('Value 1'); 
     QSTR.OtherData.push('Value 2'); 

     $.ajax({ 
      type: 'POST', 
      url: '/Omni/DoRoutine', 
      data: JSON.stringify({ obj: 'Reynor here!' }), 
      // this acctually works 
      // and at the action method I get the object[] 
      // with object[0] = 'Reynor here!' 
      // but when I use the object I really need to send I get null 
      data: JSON.stringify({ obj: QSTR }), //I get null 
      contentType: 'application/json; charset=utf-8', 
      dataType: "json", 
      success: function (msg) { 
       alert('ok'); 
      }, 
      error: function (xhr, status) { 
       alert(status); 
      } 

     }); 
    } 

這是操作方法的代碼:

  [HttpPost] 
     public ActionResult DoRoutine(object[] obj) 
     { 
      return Json(null); 
     } 

,這是什麼解決方案,以及爲什麼會出現這種情況? 謝謝

回答

0

QSTR是一個複雜的類型,所以你需要在你的post方法中使用複雜的數據。

public class QSTR 
{ 
    public string name { get; set; } 
    public string Address { get; set; } 
    public object[] OtherData { get; set; } 
} 

[HttpPost] 
public ActionResult DoRoutine(QSTR obj) 
{ 
    return Json(null); 
} 

但是如果你想只接收otherdata你應該只在發送您的阿賈克斯陣:

$.ajax({ 
    data: JSON.stringify({ obj: QSTR.OtherData }), 
    // other properties 
}); 
+0

據我所知,將可能的解決辦法,但我仍然不知道爲什麼。我在asp.net上有一個類似的方法,實際上它是一個[WebMethod],並遵循我的初始方法,它工作正常,我的意思是我有我的對象[]參數。爲什麼它不適用於MVC上的[HttpPost]方法?如果要將這些信息發送回服務器,那麼根據幾個因素,這意味着不同的數據結構?謝謝 – Overlord 2014-09-26 20:39:49

+0

@Overlord也許[這](http://stackoverflow.com/questions/9067344/net-mvc-action-parameter-of-type-object)可以幫助 – aleha 2014-09-26 21:26:36

+0

謝謝艾倫,你的回答是非常有用的找到我的解決方案 – Overlord 2014-09-27 14:51:32