Viku
Viku

Reputation: 2973

Pass an array within an object in Ajax call to MVC controller

I have an Ajax call as below from my client js files to an MVC acontroller method

From the client js files ::

var ActivityLog = new Array();
var Test={}
Test['Customer[0].Id'] = "3060_3";
Test['Customer[0].Value'] = "0";
Test['CustId'] = "1111";
Test['crl'] = true;
Test['ActNumber'] = "2222";

for (var i = 0; i < 2; i++) {
    Test['ActivityLog[' + i + ']'] ="1";
}

My Controller ActionMethod ::

 public ActionResult SaveAccountCustomerServicePlans(string CustId, IDictionary<string, Customer> Customer, bool? crl, string ActNumber, string[] ActivityLog)
{
   // Here all the parameter i am getting as null
}

My entity class

public class Customer
    {
    [DataMember]
    [Key]
    public int Id{ get; set; }


    [DataMember]
    public string Value{ get; set; }



} 

My Ajax call::

$.ajax({
        type: 'POST',

        async: true,
    });

    $.ajax({
   beforeSend: function (xhr) {
       xhr.setRequestHeader('__RequestVerificationToken', $(':input:hidden[name*="RequestVerificationToken"]').val());
   },
   type: "POST", url: "Customerss/Customermanagement/SaveAccountCustomerServicePlans", data: { Test: Test},
   success: function (data) {
       /////
   }
});

In above controller method all the parameters i am getting as null . But aif i remove ActivityLog from Test object everything works fine . Can anybody please help me to solve this issue.

Upvotes: 0

Views: 634

Answers (2)

Daniel Gpe Reyes
Daniel Gpe Reyes

Reputation: 417

try with this,

change your controller

    public ActionResult SaveAccountCustomerServicePlans(Customer model, string CustId, bool? crl, string ActNumber, List<string> ActivityLog)
    {

then in the javascript

    var ActivityLog = new Array();
    var Test = {}
    Test['Id'] = "30603";
    Test['Value'] = "0";
    Test['CustId'] = "1111";
    Test['crl'] = true;
    Test['ActNumber'] = "2222";

    for (var i = 0; i < 2; i++) {
        Test['ActivityLog[' + i + ']'] = "1";
    }

and finally in your ajax

  type: "POST", url: "Customerss/Customermanagement/SaveAccountCustomerServicePlans", data: Test,

Hope this help you

Note: in your Model class you have Id like "int" but in the javascript you are sending a string "30603_3";

Upvotes: 1

Nosboy
Nosboy

Reputation: 3

remove the plus before i like below not sure why its there

Test['ActivityLog['  i + ']'] ="1";

or remove the plus all together if you trying to save the ="1" there like below

Test['ActivityLog[' i ']'] ="1";

Upvotes: 0

Related Questions