Jquery function always return counter 0 of second parameter

I am writing a function in jquery that sends data to a controller. it is currently sending the form data to the controller ok, but when I post a list of checkboxes with the form data, it always sends a score of 0 to the 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); 
} 

      

somebody tell me where is the problem in my code, thanks.

+3


source to share


2 answers


Cannot combine data 'application/x-www-form-urlencoded'

( contentType

method serialize()

) and 'application/json'

data ( contentType

method JSON.stringify()

).

Agree, you have confirmed that you are sending only one property Subject

, which SubjectId

is typeof int

, after which you can add values SubjectId

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)
{ 
    ....

      

+1


source


I think you are using the POST method incorrectly. You are trying to mix sending data as json and as url parameters.

data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),

      

what are you sending in the data:

[
  {...},
  [{SubjectId: ''}, {SubjectId: ''}]
]

      

or



{
  1: {...},
  subjectData: [{SubjectId: ''}, {SubjectId: ''}]
}

      

or some data is passed as json, some in url?

Send all data to json and not serialize (jquery do this for you):

var data = [strudentFormData, subjectData];
$.ajax(..., data: data, ...);

      

0


source







All Articles