alka vaghela alka vaghela - 1 month ago 6
Ajax Question

pass array of array to the controller not working in asp.net mvc

I want to pass array value from view to the controller action using ajax. I have created jquery and controller method as bellow, but its not working.

in my javascript file,

$("#btnSave").click(function () {
var data = [];
$("#utiltyTable tr.maintr").each(function () {

var selectedMail = [];
var selectedMobile = [];

var categoryId = $(this).find("td.uCategory").find("input[type='hidden']").val();

$(this).find("td.uEmail").find("select :selected").map(function (i, el) {
selectedMail.push({ "value": $(el).val(), "item": $(el).text() });
});

$(this).find("td.uSMS").find("select :selected").map(function (i, el) {
selectedMobile.push({ "value": $(el).val(), "item": $(el).text() });
});

data.push({ categoryId: categoryId, selectedMail: JSON.stringify(selectedMail), selectedMobile: JSON.stringify(selectedMobile) })


});

console.log(data);

$.ajax({
url: '@Url.Action("UtilityEmailSMS", "Account")',
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function (data) {

}
});

});


Controller action method as bellow,

[HttpPost]
public ActionResult UtilityEmailSMS(string[] data)
{

return View();
}


I am getting string[] array.but all key value as null
enter image description here

Answer Source

You should accept array of objects instead of string, as you are passing object array from ajax.

So create a model for same.

public class Mail
  {
    public string value {get;set;}
    public string item {get;set;}
  }

public class Test
{
    public string categoryId {get;set;}
    public Mail[] selectedMail {get;set;}
    public Mail[] selectedMobile {get; set;}
}

Then

    [HttpPost]
    public ActionResult UtilityEmailSMS(Test[] data)
    {

        return View();
    }