How to pass multiple arrays in one ajax call to controller method ASP.net MVC 4

13,277

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.

Share:
13,277
user2701646
Author by

user2701646

Updated on June 05, 2022

Comments

  • user2701646
    user2701646 almost 2 years

    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)