How to pass multiple arrays in one ajax call to co

2020-07-26 07:44发布

I have multiple arrays that I want to pass from view into a controller method. For that purpose, I converted those arrays into JSON objects. Then, create the AJAX call, but how do I send those JSON objects at once?

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条回答
虎瘦雄心在
2楼-- · 2020-07-26 08:03

Like this :

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

and on server

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

Or if you want to send a single object to server, create new object with all 4 arrays as properties and then stringify and send that object.

查看更多
看我几分像从前
3楼-- · 2020-07-26 08:20

As always start by writing a view model that will hold the information:

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

that your controller action will take:

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

and now all that's left is to send the corresponding JSON object:

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

In this example I have used string arrays as properties to the view model but you could of course use arbitrarily complex objects depending on the data you are trying to send.

查看更多
登录 后发表回答