2

hi guys i'm posting some data to controller using jquery ajax, but i am getting null values in my controller,

jQuery code is:

$('#registerCompOff').click(function() {

    var compOff = [];
    $('div').each(function() {
        var curRow = {};
        curRow.Description = $(this).find('.reason').val();
        curRow.CompOffDate = $(this).find('.datefieldWithWeekends').val();
        if (curRow.Description != null && curRow.CompOffDate != null) {
            compOff.push(curRow);
        }
    });
    $.ajax({
        type: 'POST',
        url: this.href,
        dataType: 'json',
        data: compOff

    });

    return $('form').valid();

});​

compOff is not null I have checked that...

controller is:

 [HttpPost]
        public ActionResult RegisterCompOff(RegisterCompOff[] registerCompOff)
        {

            //return View();
        }

can you tell me where i'm going wrong?

tereško
  • 58,060
  • 25
  • 98
  • 150
Piyush Sardana
  • 1,748
  • 4
  • 19
  • 33

3 Answers3

3

Given your original code, change in $.ajax -> data: JSON.stringify(compOff) then add contentType: "application/json; charset=utf-8" and finally change parameter name of controller's action to public ActionResult RegisterCompOff(RegisterCompOff[] compOff).
Model binding should kick off then. It did for me.

lucask
  • 2,290
  • 24
  • 19
1

Edited:

try this :

 $.ajax({
        type: 'POST',
        url: this.href,
        dataType: 'json',
        traditional: true,
        data: 
        {
             CompOffList: compOff 
        }
    });

and change your controller like this :

[HttpPost]
        public ActionResult RegisterCompOff(List<RegisterCompOff> CompOffList)
        {

            //return View();
        }

hope this helps

Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63
0

Your r passing javascript object as data wherease jquery ajax method expects a key/value pair list. Try this

data:{Description:compOff.Description, CompOffDate:compOff.CompOffDate}
ZafarYousafi
  • 8,640
  • 5
  • 33
  • 39