2016-01-22 110 views
0

我想通过一个javascript数组,其中的值来自多选框。但是,当它遇到该操作时,我从ajax get请求中获得null回来。我试图设置一个断点,它返回为空。这是我行动的签名使用Ajax将数组传递给mvc5动作

public JsonResult GetMessages(List<string> id, string searchText) 

,这里是我的Ajax调用:

$.get("Dashboard/GetMessages", $.param({ "id": JSON.stringify(selectedID), "searchText": InputSearch }, true) 
     , function (result) { 
     for (var item = 0; item < result.length; item++) { 
      var newMessageEntry = "<tr><td>" + result[item] + "</td></tr>" 
     } 
    }) 
+0

向我们展示你是如何构建'selectedID'? – ramiramilu

+0

@ramiramilu var selectedID = $(“select#messages”)。val(); – Johnathon64

回答

1

要通过在阿贾克斯POST阵列中的数据,使用下面的代码。

控制器动作 -

[HttpPost] 
public JsonResult GetMessages(List<string> id, string searchText) 
{ 
     return Json(true); 
} 

而jQuery代码应该是 -

$.ajax({ 
    url:"/Home/GetMessages", 
    type:"POST", 
    data:JSON.stringify({ id: selectedID, searchText: InputSearch }), 
    contentType:"application/json; charset=utf-8", 
    success: function(result){ 
     console.log(result); 
    } 
}); 

当你运行应用程序时,你应该得到的数据如下图所示 -

enter image description here

要使GET请求,使用下面代码。

控制器行动 -

public JsonResult GetMessages(List<string> id, string searchText) 
{ 
    return Json(true); 
} 

和jQuery代码应该是 -

$.ajax({ 
    url:"/Home/GetMessages", 
    type:"GET", 
    data:{ id: selectedID, searchText: InputSearch }, 
    contentType: "application/json; charset=utf-8", 
    // Make sure we have to set Traditional set to true 
    traditional: true, 
    success: function(result){ 
     console.log(result); 
    } 
}); 

和输出将是 -

enter image description here

+0

但是这应该是一个获取操作,使用POST是否正常? – Johnathon64

+0

我建议使用'POST'来传递更复杂的数据(强类型数据),并使用'GET'作为简单参数和普通查询字符串,比如字符串和不敏感数据。 – ramiramilu