Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Function always return count 0 of second parameter

i am writing a function in jquery which post the data to controller. currently it is posting form data to controller fine but when i post checkbox list with form data then it send always count 0 in controller here is my code.

    function SubmitForm() {
    var studentFormData = $("#frmStudent").serialize();
    debugger;
    var SubjectArraydata = new Array();

    $(".chkSubject:checked").each(function () {
        var row = {
            "SubjectId": $(this).data("id")
        };
        SubjectArraydata.push(row);
    });

    $.ajax({
        url: '@Url.Action("StudentForm", "Student")',
        type: "POST",
        dataType: "json",
        data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
        async: true,

        success: function (msg) {

        },
        error: function () {

        }
    });
}

Controller:

[HttpPost] 
public ActionResult StudentForm(Student student, List<Subject> subjectData)
{ 
   return Json(true); 
} 

any one tell me where is the problem in my code thank you.

like image 524
Ammar Avatar asked Sep 12 '26 22:09

Ammar


1 Answers

Your cannot mix 'application/x-www-form-urlencoded' data (the contentType of your serialize() method) and 'application/json' data (the contentType of the JSON.stringify() method) like that.

Sinve you have confirmed that your only submitting one property of Subject, which is SubjectId and is typeof int, then you can append the SubjectId values to the serialized data.

var studentFormData = $("#frmStudent").serialize();
$(".chkSubject:checked").each(function () {
    studentFormData += '&' + $.param({ SubjectIds: $(this).data("id") });
};
$.ajax({
    url: '@Url.Action("StudentForm", "Student")',
    type: "POST",
    dataType: "json",
    data: studentFormData,
    success: function (msg) {
    },
    error: function () {
    }
});

and change your controller method to

[HttpPost] 
public ActionResult StudentForm(Student student, List<int> SubjectIds)
{ 
    ....

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!