使用AJAX将JavaScript数组发布到asp.net MVC控制器

我的控制器:

[HttpPost] public ActionResult AddUsers(int projectId, int[] useraccountIds) { ... } 

我想通过AJAX将参数发布到控制器。 传递int projectId不是问题,但是我无法发布int[]

我的JavaScript代码:

 function sendForm(projectId, target) { $.ajax({ traditional: true, url: target, type: "POST", data: { projectId: projectId, useraccountIds: new Array(1, 2, 3) }, success: ajaxOnSuccess, error: function (jqXHR, exception) { alert('Error message.'); } }); } 

我尝试使用测试arrays,但没有成功。 :(我也尝试设置traditional: truecontentType: 'application/json; charset=utf-8'但是没有成功…

发布到我的控制器的int[] useraccountIds始终为null。

您可以定义视图模型:

 public class AddUserViewModel { public int ProjectId { get; set; } public int[] userAccountIds { get; set; } } 

然后调整您的控制器操作以将此视图模型作为参数:

 [HttpPost] public ActionResult AddUsers(AddUserViewModel model) { ... } 

最后调用它:

 function sendForm(projectId, target) { $.ajax({ url: target, type: 'POST', contentType: 'application/json', data: JSON.stringify({ projectId: projectId, userAccountIds: [1, 2, 3] }), success: ajaxOnSuccess, error: function (jqXHR, exception) { alert('Error message.'); } }); } 

在JS中:

 var myArray = new Array(); myArray.push(2); myArray.push(3); $.ajax({ type: "POST", url: '/MyController/MyAction', data: { 'myArray': myArray.join() }, success: refreshPage }); 

在MVC / C#中:

 public PartialViewResult MyAction(string myArray) { var myArrayInt = myArray.Split(',').Select(x=>Int32.Parse(x)).ToArray(); //My Action Code Here } 

使用$ .Ajax(),您可以轻松地将数据从javascript传输到MVC中的Controller。

就像,

 var uname = 'John Doe'; $.ajax({ url: "/Main/getRequestID", // This is path of your Controller with Action Result. dataType: "json", // Data Type for sending the data data: { // Data that will be passed to Controller 'my_name': uname, // assign data like key-value pair // 'my_name' like fields in quote is same with parameter in action Result }, type: "POST", // Type of Request contentType: "application/json; charset=utf-8", //Optional to specify Content Type. success: function (data) { // This function is executed when this request is succeed. alert(data); }, error: function (data) { alert("Error"); // This function is executed when error occurred. } )}; 

然后,在控制器端,

 public ActionResult getRequestID(String my_name) { MYDBModel myTable = new Models.MYDBModel(); myTable.FBUserName = my_name; db.MYDBModel.Add(myTable); db.SaveChanges(); // db object of our DbContext.cs //return RedirectToAction(“Index”); // After that you can redirect to some pages… return Json(true, JsonRequestBehavior.AllowGet); // Or you can get that data back after inserting into database.. This json displays all the details to our view as well. } 

参考。 在Java中将数据从Java脚本发送到Controller

将serializable属性放在类上。 然后它会尝试将您传递的javascript对象转换为C#类。

在JS中:

 { ProjectId = 0, userAccountIds = [] } // C# [Serializable] public class AddUserViewModel { public int ProjectId { get; set; } public int[] userAccountIds { get; set; } } 

如果要将数组传递给mvc引擎,请多次发送输入。 将您的代码更改为以下内容:

 function sendForm(projectId, target) { var useraccountIds = new Array(1, 2, 3); var data = { projectId: projectId }; for (var i = 0; i < useraccountIds.length; i++) { $.extend(true, data, {useraccountIds: useraccountIds[i]}); } $.ajax({ traditional: true, url: target, type: "POST", data: data, success: ajaxOnSuccess, error: function (jqXHR, exception) { alert('Error message.'); } }); 

}

除非您指定ajax请求(Post / Get)将属性traditional设置为true,否则它将无法工作。 有关详细信息,请参阅此问题 。