我想知道是否有人知道如何将对象的Javascript数组传递给接受元组数组的MVC操作方法。

例:

Javascript:

var objectArray =
[
    { id: 1, value: "one" },
    { id: 2, value: "two" }
];

$.post('test',objectArray);

MVC Controller 操作:
public JsonResult Test((int id, string value)[] objectArray)
{
    return Json(objectArray != null);
}

不幸的是,由于C#代码中的objectArray为null,因此我给出的示例始终返回false。

最佳答案

您无法执行此操作,因为就像错误所说:元组没有parameterless constructor,因此模型绑定(bind)器无法实例化它。

另外,您可以阅读有关Model Binding的更多信息。

其中一个短语说:



您可以使用另一种方法:

首先,您必须使用JSON.stringify方法发送给定的数组
JSON.stringify() javascript 对象转换为json文本,并将其存储在string中。

AJAX

objectArray = JSON.stringify({ 'objectArray': objectArray });
$.ajax({
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    url: 'test',
    data: objectArray ,
    success: function () {

    }
});

在服务器端方法中,您必须传递对象列表作为参数。
[HttpPost]
public void PassThings(List<Thing> objectArray )
{

}

public class Thing
{
    public int Id { get; set; }
    public string Value { get; set; }
}

07-24 09:51
查看更多