如何在一个ajax调用中将多个数组传递给控制器​​方法ASP.net MVC 4

时间:2013-08-21 16:33:50

标签: jquery ajax json asp.net-mvc-4

我有多个数组,我想从视图传递到控制器方法。为此,我将这些数组转换为JSON对象。然后,创建AJAX调用,但是如何一次发送这些JSON对象?

var json_InstallationControl = JSON.stringify(array_installationControl);
var json_HardwareGUID = JSON.stringify(array_HardwareGUID);
var json_InstallAppID = JSON.stringify(array_InstallAppID);
var json_MACAddress = json.stringify(array_MACAddress);

$.ajax({
url: "@Url.Content("~/Home/ActivationManagement")",
type: "POST",
contentType: "application/json",
data: { jsonData: json_InstallationControl },
success: function(){
console.log('success!!');
}
})

[HttpPost]
public ActionResult ActivationManagement(String jsonData)

2 个答案:

答案 0 :(得分:9)

一如既往地编写一个包含信息的视图模型:

public class MyViewModel
{
    public string[] InstallationControls { get; set; }
    public string[] HardwareGUIDs { get; set; }
    public string[] InstallAppIDs { get; set; }
    public string[] MACAddresses { get; set; }
}

您的控制器操作将采取:

[HttpPost]
public ActionResult ActivationManagement(MyViewModel model)
{
    ...
}

现在剩下的就是发送相应的JSON对象:

var data = JSON.stringify({
    installationControls: array_installationControl,
    hardwareGUIDs: array_HardwareGUID,
    installAppIDs: array_InstallAppID,
    macAddresses: array_MACAddress
});

$.ajax({
    url: "@Url.Content("~/Home/ActivationManagement")",
    type: "POST",
    contentType: "application/json",
    data: { data: data },
    success: function() {
        console.log('success!!');
    }
});

在这个例子中,我使用字符串数组作为视图模型的属性,但您当然可以使用任意复杂的对象,具体取决于您尝试发送的数据。

答案 1 :(得分:0)

像这样:

$.ajax({
url: "@Url.Content("~/Home/ActivationManagement")",
type: "POST",
contentType: "application/json",
data: {
 json_InstallationControl: json_InstallationControl,
json_HardwareGUID :json_HardwareGUID,
json_InstallAppID :json_InstallAppID,
json_MACAddress :json_MACAddress 
},
success: function(){
console.log('success!!');
}
})

并在服务器上

public ActionResult ActivationManagement(String json_InstallationControl,String json_HardwareGUID ,String json_InstallAppID,String json_MACAddress )

或者,如果要将单个对象发送到服务器,请创建包含所有4个数组作为属性的新对象,然后进行字符串化并发送该对象。