如何使用Ajax get向Action发送一个整数值数组?

时间:2013-02-28 11:15:10

标签: asp.net-mvc jquery

我的操作接受一个整数值数组:

public ActionResult ActionName(int firstParamId, int secondParamId, int[] contactIds)

我正在使用以下代码,但未发送所选的整数数组。

function btnSend_onclick() {

            var firstParamId = 1;
            var secondParamId= 2;
            var selectedContactIds = [];

            $('#ContactsListContainer input:checked').each(function() {
                selectedContactIds.push($(this).val());
            });

            var params = {
                firstParamId : firstParamId ,
                secondParamId: secondParamId,
                contactIds: selectedContactIds
            };

            $.get('/ControllerName/ActionName', JSON.stringify(params))
                .done(function(data, status) {
                    alert("Data: " + data + "\nStatus: " + status);
                })
                .fail(function(data) {
                    debugger;
                    alert(data.responseText);
                });
        }

我收到以下每个参数的错误:

    The parameters dictionary contains a null entry for parameter 'firstParamId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Actionname(Int32, Int32, Int32[])' 
in 'AppNamespace.MvcUI.Controllers.ControllerName'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters

上述代码有什么问题?

1 个答案:

答案 0 :(得分:0)

  try this , 

     var param={
      contactIds:[]
     };

        while pushing do param.contactIds.push(...);

       $.get('/ControllerName/ActionName',
        {                   
                "param":  JSON.stringify(param)
        })
        .done(function(data, status) {
                alert("Data: " + data + "\nStatus: " + status);
        })
        .fail(function (data, status) {
                 alert("Data: " + data + "\nStatus: " + status);
        });

这里有一个全局变量,我创建了数组,然后我推送了该数组中的所有值。然后在发送时使用JSON.stringify(param)。它对我有效。

在行动中,

String param = (String) request.getParameter("param");
 JSONObject searchCriteriaJSONObj = (JSONObject) JSONSerializer.toJSON(param);


 String paramStr = searchCriteriaJSONObj.getString("contactIds");
 List<JSONObject> skillsJSONObj = (List<JSONObject>) JSONArray.fromObject(paramStr);

它在struts2中,在struts1中你可能需要使用插件来进行jSOn转换