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

时间:2013-04-03 08:32:37

标签: javascript ajax asp.net-mvc jquery

我的控制器:

[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.');
        }
    });
}

我尝试使用测试阵列,但没有成功。 :( 我还试图设置traditional: truecontentType: 'application/json; charset=utf-8',但也没有成功......

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

6 个答案:

答案 0 :(得分:34)

您可以定义视图模型:

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.');
        }
    });
}

答案 1 :(得分:15)

在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
}

答案 2 :(得分:2)

使用$ .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.
        }
)};

然后,在Controller端,

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.
}

参考。 Send Data from Java Script to Controller in MVC

答案 3 :(得分:1)

如果要将数组传递给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.');
    }
});

}

答案 4 :(得分:0)

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

JS中的

{
   ProjectId = 0, 
   userAccountIds = []
}

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

答案 5 :(得分:0)

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