JQuery将数据发布到MVC Action Method?

时间:2013-03-26 21:00:44

标签: jquery asp.net-mvc model-view-controller

我要做的就是将一个字符串/整数数组传递给mvc动作方法。 但数据总是以null为单位,我做错了什么?

MVC控制器

[HttpPost]
 public ActionResult MyAction(List<string> ids)
 {
   // do something with array
   // But it's null
      return View();
 }

JQuery的

$.post("/MyController/MyAction", JSON.stringify(ids), function () { alert("woohoo"); }, "application/json");

将数据发布到操作结果

["156"]

1 个答案:

答案 0 :(得分:3)

尝试:

... JSON.stringify({ ids : ids }), ...

我很确定模型绑定器不确定列表/数组也被绑定了。

考虑:

[HttpPost]
public ActionResult MyAction(List<string> ids, List<string> blah)
{
}

如果JSON仅作为一个值数组传递,那么哪个参数也要绑定? JSON可能比FORMS提交复杂得多,因此它还需要更多的定义。

例如,以下内容适用于之前的考虑。

{
  ids : ["asdf","asdf"],
  blah : ["qwer", "qwer"]
}

<强>更新

为了正确发送json,需要进行以下ajax调用:

$.ajax({
  type: "POST",
  url: "/Home/Index",
  data: JSON.stringify( ids ),
  contentType: "application/json; charset=utf-8"
});

Post中的最后一个参数(您指定application/json)是从服务器返回的内容。默认情况下,a。.Post将执行表单编码(application/x-www-form-urlencoded)contentType,它似乎硬编码到快捷方法中。要设置contentType,您必须使用长手版本$ .ajax。

相关问题