jQuery AJAX调用传递值数组的Controller操作

时间:2018-09-26 18:28:59

标签: javascript jquery ajax model-view-controller

我试图将复选框值的数组从MVC中的Ajax形式传递给控制器​​操作。这是我的代码:

表单(以模式形式):

@using (Ajax.BeginForm("GetPrintableProject", "Project", null, new AjaxOptions { HttpMethod = "POST"}, new { @id = "PrintProjectFormId"))
 {
 <input type="hidden" name="projectId" id="projectId" value="">

}

一些jQuery可以获取一组复选框值:

selectedProjects = projectsGrid.$('input[type="checkbox"]').serializeArray();

var projects = [];

$(selectedProjects).each(function (i, field) {
    projects.push(field.value);
});
//the hidden field in a modal I'm using
$('#projectId').val(projects.toString());

以及我要提交的功能:

$("#PrintProjectFormId").submit(function (event) {

event.preventDefault();
event.stopImmediatePropagation();

var action = $("#PrintProjectFormId").attr("action");
var dataString = new FormData($("#PrintProjectFormId").get(0));

$.ajax({
   type: "POST",
   url: action,
   data: dataString,
   dataType: "json",
   contentType: false,
   processData: false,
   success: function (result) {
            //stuff I'll get to later
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("There was a problem retrieving this project");
        }
        });
    });

,然后是控制器签名:

[HttpPost]
public JsonResult GetPrintableProject(Guid[] projectId)

如果我传递单个值,则工作正常,但如果我传递多个值,则控制器仅获得“ null”。认为我在这里缺少一些简单的东西。预先感谢。

3 个答案:

答案 0 :(得分:1)

除非您需要,否则我建议不要更改默认选项值。 将参数创建为JSON对象,并将其传递给$.ajax

来自jQuery API for AJAX

  

processData(默认值:true)

     

类型:布尔值

     

默认情况下,作为对象传递到data选项的数据(从技术上讲,不是字符串)将被处理并转换为查询字符串,以适合默认的内容类型“ application / x-www-form” -urlencoded”。如果要发送DOMDocument或其他未处理的数据,请将此选项设置为false。

将此值设置为false会在尝试将多个值传递给操作时引起问题,除非您在控制器功能内进行处理。

var action = $("#PrintProjectFormId").attr("action");

//fill projects array

$.ajax({
  type: "POST",
  url: action,
  data: {
    projectId: $("#PrintProjectFormId").val(),
    "projects": projects
  },
  success: function(result) {
    //stuff I'll get to later
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert("There was a problem retrieving this project");
  }
});

答案 1 :(得分:0)

请尝试以下操作:

 type: "POST",
   url: action, 
   data: {dataString:dataString, dataString1:dataString2, dataString2:dataString2},

格式为:index:value

答案 2 :(得分:0)

由于您不是传递类而是数组,因此您的数据字符串应类似于:

   type: "POST",
   url: action, 
   data:
      [
        "6ccf7071-9b73-4e61-8736-58a842c131d0",
        "9e6c2748-18b5-4a53-a306-eb539c8b7dee",
        "5aa8901a-2c03-42d3-bf06-89f66e3797a4",
        "da5556bf-32aa-4f41-a64a-6e95fa2595c1"
      ],

也可以尝试在ActionMethod中添加FromBody,例如:

[HttpPost]
public JsonResult GetPrintableProject([FromBody]Guid[] projectId)