2014-09-26 52 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