21

我的控制器:

[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: true,或者contentType: 'application/json; charset=utf-8'也没有成功...

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

4

6 回答 6

39

您可以定义一个视图模型:

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.');
        }
    });
}
于 2013-04-03T08:35:02.883 回答
18

在 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
}
于 2013-11-07T14:59:12.427 回答
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.
        }
)};

然后,在控制器端,

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 Script 发送到 MVC 中的控制器

于 2013-08-27T10:34:54.557 回答
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.');
    }
});

}

于 2013-04-03T08:41:01.367 回答
0

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

在 JS 中:

{
   ProjectId = 0, 
   userAccountIds = []
}

// C#
[Serializable] 
public class AddUserViewModel
{
    public int ProjectId { get; set; }
    public int[] userAccountIds { get; set; }
}
于 2013-04-03T08:50:21.287 回答
0

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

于 2015-03-23T23:23:31.803 回答