kaushik guru

kaushik guru

  • 1.4k
  • 252
  • 27.3k

ajax sends null data to controller but on consolelog posts all the val

Apr 25 2023 10:22 AM

Dear team i have array of object which i am trying to send to controller as a list , but in controller if i use(List<model> data) its is always null, but if i use (string data ) it has the value from the ajax call 

the below is my ajax call 

function fnNExt() {
            var dataToSave = [];
            $('#insurancetable tbody tr').each(function () {
                var empid = '@ViewBag.empid';
                var empInsuranceid = $(this).find('[name="chkSelect"]').val();
                var empinsuranceselectid = $(this).find('[name = "chkSelect"]').attr('id');
                var insuranceCmts = $(this).find('[name="txtNominee"]').val();
                dataToSave.push({ EmployeeId: empid, IsRelationshipChecked: empInsuranceid, RelationshipComments: insuranceCmts, EmployeeInsuranceId: empinsuranceselectid });
                console.log("111");
                //console.log(items);
            });
            var items = JSON.stringify(dataToSave);
            var empid = 1;
            console.log(items);
            $.ajax({
                type: "POST",
                dataType: "JSON",
                url: "/HRValidation/SaveInsuranceNominee",
                data: "emp=" +items,
                success: function (response) {
                    console.log(response);
                },
                error: function (error) {
                    console.log(response);
                }
            });
        }

on console the items variable i am getting this 

[{"EmployeeId":"1","IsRelationshipChecked":"null","RelationshipComments":"null","EmployeeInsuranceId":"2"},{"EmployeeId":"1","IsRelationshipChecked":"null","RelationshipComments":"null","EmployeeInsuranceId":"3"}]

When my controller is as follows i am getting the data from ajax to the controller
 

public IActionResult SaveInsuranceNominee(string emp)
        {}

BUt the problem is i need to loop through each data and update in the db

i want to write my controller as below

public IActionResult SaveInsuranceNominee(List<InsuranceValidateVM> emp)
        {
            foreach(var items in emp)
{
//update db
}
}

When i use the above method  the List<InsurancevalidateVM> emp is always null or count is 0

 

Please help 

 

My model is as follows

public class InsuranceValidateVM
    {
        public int Employeeid { get; set; }

        public int employeeInsuranceId { get; set; }

        public int ischecked { get; set; }

        public string nomineeName { get; set; }
    }

 


Answers (3)