Search code examples
c#ajaxasp.net-core-mvc

Cannot transfer object collection from view to controller


I am not able to transfer collection objects from View to Controller in my ASP.Net Core MVC C# application. In my Index.cshtml, I have a jQuery datatable and I able to load data into that jQuery Datatable from database. I want to save the records in the DataTable to DB. But when I transfer data from View to Controller, I am getting null value in the Controller.

In Index.cshtml,

    function SaveNewDoor() {

       var newDoorData = [];
       var table1 = $('#newTable').DataTable();        
    
       table1.rows().every(function (rowIdx, tableLoop, rowLoop) 
       {
            var data = this.data();                        
                          
            var customModel = new Object();
            customModel.siteCode = data[0];     // here all values are correct
            customModel.legacyDoor = data[1];
            customModel.brand = data[6];
            customModel.buyingGroup = data[7];
            customModel.settingname = data[9];
            
            newDoorData.push(customModel);                                     
                   
       });               
    
        $.ajax({
             url: '@Url.Action("SaveSettings", "DOOR_MANAGEMENT")', 
             type: 'POST',
             contentType: 'application/json',            
             data: JSON.stringify({ newDoorData }),

             success: function (result) { alert('Door Data changes saved'); },
             error: function (xhr, status, error) {                
                    console.log("Error:", error);
                    console.log("Status:", status);
                    console.log("XHR:", xhr);
             }
        });
     }

In my Controller, I am getting empty value.

    [HttpPost]
    public ActionResult SaveSettings(vmNewDoor[] model) // here model is empty
    {
    }

The vmModel class is shown below :

     public class vmNewDoor
     {     
       public int siteCode { get; set; }
       public int legacyDoor { get; set; }
       public string brand { get; set; }
       public string buyingGroup { get; set; }
       public string settingName { get; set; }
       public int settingId { get; set; }
       public string userId { get; set; }
       public string status { get; set; }
    }

I am not able to understand what is the problem ?? How I can pass an object collection from view to controller ???


Solution

  • I think you are wrapping your array into an object that doesn't match to your action parameters. Change the line with JSON.stringify({newDoorData}) to JSON.stringify(newDoorData).

    $.ajax({
         ...          
         data: JSON.stringify(newDoorData),
         ...
        });
    

    Secondary, for protection purpose I would add [FromBody] to your action:

    [HttpPost]
    public ActionResult SaveSettings([FromBody] vmNewDoor[] model) // here model is empty
    {
    }
    

    You also have a typo in your js code that doesn't match to your class prop name:

    customModel.settingname = data[9];
    // should be
    customModel.settingName = data[9];
    

    Depends on JSON parser in your API, you might want to make data class properties with PascalCase. Example:

    public class vmNewDoor
    {     
       public int SiteCode { get; set; }
       public int LegacyDoor { get; set; }
       public string Brand { get; set; }
       public string BuyingGroup { get; set; }
       public string SettingName { get; set; }
       public int SettingId { get; set; }
       public string UserId { get; set; }
       public string Status { get; set; }
    }
    

    For debugging purpose try to use browser's developer tools. In the network tab it will tell you exactly what data structure your request is sending out to API. It will help you to debug it in the future.