使用jquery和ajax将json对象发布到mvc控制器

我试图从表单中提交一些值到我的mvc控制器。

这是我的控制器:

//Post/ Roles/AddUser [HttpPost] public ActionResult AddUser(String json) { Log.submit(json); return View(); } 

这是js:

  function submitForm() { var usersRoles = new Array; $("#dualSelectRoles2 option").each(function () { usersRoles.push($(this).val()); }); console.log(usersRoles); jQuery.ajax({ type: 'POST', url: "@Url.Action("AddUser")", contentType: "application/json; charset=utf-8", datatype: 'json', data: JSON.stringify(usersRoles), success: function (data) { alert(data); }, failure: function (errMsg) { alert(errMsg); } }); } 

当我在控制器上调试时,我的参数是null? console.log(usersRoles)为我提供数据。

我做错了什么?

如何在控制器中接收json对象?

我在你的代码中看到你试图将ARRAY传递给POST动作。 在这种情况下,按照以下工作代码 –

    

控制器动作将是 –

  public ActionResult AddUser(List Roles) { return null; } 

然后当你点击按钮 –

在此处输入图像描述

而不是接收json字符串,模型绑定更好。 例如:

 [HttpPost] public ActionResult AddUser(UserAddModel model) { if (ModelState.IsValid) { return Json(new { Response = "Success" }); } return Json(new { Response = "Error" }); }  

我做错了什么?

你必须将html转换为javascript对象,然后作为json通过JSON.Stringify的第二步。

如何在控制器中接收json对象?

视图:

   var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true }); $.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) }); 



控制器:

 public void PostRawJson(string json) { var order = System.Web.Helpers.Json.Decode(json); var orderDate = order.OrderDate; var secondOrderId = order.Item[1].Id; }