Eyal
Eyal

Reputation: 4763

Ajax to C# controller: How to pass an Array of objects along with other data

I have the following code:

Class:

public class EngineGroup
{      
    public string CategoryName { get; set; }  
    public OemPart[] ArrOemParts { get; set; }

}

public class OemPart {
    public string IdInDiagram { get; set; }
    public string Sku { get; set; }
    public string OemName { get; set; }
}

Controller:

 public IActionResult Insert(EngineGroup eg){

 }

JavaScript:

            var formData = new FormData();     
            formData.append("CategoryName", groupEngineName);     
            formData.append("ArrOemParts", arrOemParts); // --  >>> this is an array of objects

 $.ajax({
            type: "POST",
            data: formData,
            url: "/Insert",
            dataType: 'json',
            contentType: false,
            processData: false,

When I am sending the FormData to the controller, the array of objects is empty while the rest of the data is successfully passed to the controller. I was trying to do JSON.stringify(formData) with no luck...

Upvotes: 1

Views: 153

Answers (1)

Eyal
Eyal

Reputation: 4763

 public class OemPart {
        public string IdInDiagram { get; set; }
        public string Sku { get; set; }
        public string OemName { get; set; }
    } 

[HttpPost]
        [IgnoreAntiforgeryToken(Order = 2000)]
        public IActionResult InsertCategoryAndOemPart([FromBody] OemPart[] oemPart, string categoryName)
        {

 $.ajax({
            type: "POST",
            data: JSON.stringify(arrOemParts),
            url: "/admin/engineGroup/InsertCategoryAndOemPart/?categoryName=" + categoryName 
            contentType: 'application/json; charset=utf-8'

Upvotes: 1

Related Questions