jQuery 将带有 AJAX 的 JavaScript 数组发布到 asp.net MVC 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15782417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:47:55  来源:igfitidea点击:

Post JavaScript array with AJAX to asp.net MVC controller

javascriptajaxasp.net-mvcjquery

提问by mosquito87

My controller:

我的控制器:

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

I'd like to post the parameters to the controller via AJAX. Passing the int projectIdisn't a problem, but I can't manage to post the int[].

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

My JavaScript code:

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

I tried it with a test array but no success. :( I also tried to set traditional: true, or contentType: 'application/json; charset=utf-8'but no success as well ...

我用测试数组尝试过,但没有成功。:(我也尝试设置traditional: true,或者contentType: 'application/json; charset=utf-8'也没有成功......

The int[] useraccountIdsposted to my controller is always null.

int[] useraccountIds贴到我的控制器总是空。

回答by Darin Dimitrov

You could define a view model:

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

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

then adapt your controller action to take this view model as parameter:

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

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

and finally invoke it:

最后调用它:

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

回答by Denis Besic

In JS:

在JS中:

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

In MVC/ C#:

在 MVC/C# 中:

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

回答by Nikhil Prajapati

Using $.Ajax(), you can easily get the data from javascript to the Controller in MVC.

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

As like,

就像,

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

then, on the Controller side,

然后,在控制器端,

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

Reference. Send Data from Java Script to Controller in MVC

参考。 在 MVC 中将数据从 Java 脚本发送到控制器

回答by Rabolf

if you want to pass an array to mvc engine, send the input multiple times. change your code to the following :

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

}

}

回答by marko

Put the serializable attribute on the class. Then it will try to convert the javascript object you are passing to the C# class.

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

in JS:

在JS中:

{
   ProjectId = 0, 
   userAccountIds = []
}

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

回答by Mostafa

It won't work unless you specify that the ajax request (Post/Get) has the property traditionalis set to true. Please refer to this questionfor more details.

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