0

I am trying to make an http post using jquery to the Web API controller, I am posting an array of objects to the controller but when is gets to the server the array is empty.

javascript

        var url = "api/actuary/" + $("#ActuaryId").val() + "/documents/";
        var inputs = $("#proofOfTraining input[type='checkbox']");
        var courseAttended = []
        inputs.each(function (ind, val) {
            var course = {};
            course["IsDone"] = $(val).is(":checked");
            course["Title"] = $(val).attr("name");
            course["ActuaryId"] = $("#ActuaryId").val();
            courseAttended.push(course);
        });
        console.log(courseAttended)
        $.post(url, JSON.stringify({ courseAttended }), function (response) {
            console.log(response)
        })

post Data

enter image description here

controller

    [Route("api/actuary/{actuaryId:long}/documents/")]
    [HttpPost]
    public async Task<IHttpActionResult> uploadCourseTrainingProofAsync(List<CourseModel> courseAttended)
    {
        try
        {
            using (Data.ADPDB db = new Data.ADPDB())
            {
                foreach (CourseModel course in courseAttended)
                {
                    var tempDoc = new documents();
                    tempDoc.ActuaryId = course.ActuaryId;
                    tempDoc.Document = null;
                    tempDoc.DocumentTypeId = -1;
                    tempDoc.Done = course.IsDone;
                    tempDoc.Title = course.Title;

                    db.documents.Add(tempDoc);
                }
                await db.SaveChangesAsync();
            }
            return Ok();
        }
        catch (Exception ex) {
            return InternalServerError(ex.InnerException);
        }
    }

Model

    public class CourseModel
{
    public int ActuaryId { get; set; }

    public string Title { get; set; }

    public bool IsDone { get; set; }
}
11
  • can we see the array of objects you are passing, and if you are using post then why dont you pass actuaryId in the body ? Commented Oct 22, 2018 at 7:13
  • JSON.stringify({ courseAttended: courseAttended }) Commented Oct 22, 2018 at 7:14
  • 1
    Try just posting JSON.stringify(courseAttended); This looks like you're sending an object to your controller, rather than an array. Commented Oct 22, 2018 at 7:17
  • try with JSON.stringify( courseAttended ) Commented Oct 22, 2018 at 7:24
  • 1
    Thanks RoryMcCrossan. @TiisetsoTjabane you can check this question too it has some good answers: stackoverflow.com/questions/13242414/… Commented Oct 22, 2018 at 9:10

2 Answers 2

1

This is what ended up working for me.

Javascript

        var inputs = $("#proofOfTraining input[type='checkbox']");

        var courseAttended = []
        inputs.each(function (ind, val) {
            var course = {};
            course["IsDone"] = $(val).is(":checked");
            course["Title"] = $(val).attr("name");
            course["ActuaryId"] = parseInt($("#ActuaryId").val());
            courseAttended.push(course);
        });

        $.ajax({
            url: "api/actuary/" + $("#ActuaryId").val() + "/documents/",
            cache: false,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(courseAttended),
            dataType: "json",
            success: function (data) {
                console.log(data)
            }
        })

Controller:

    [Route("api/actuary/{actuaryId:long}/documents/")]
    [HttpPost]
    public async Task<IHttpActionResult> 
    uploadCourseTrainingProofAsync(List<CourseModel> courseAttended)
    {
     //.....
    }

I m more interested as to why I have specify the rest of the details in the ajax request.

Thanks for the suggestions.

Sign up to request clarification or add additional context in comments.

1 Comment

Most likely the original code did not specify the correct content type (JSON) so the model binder was unable to bind the incoming data to the model.
0

you have specify Content-Type for your request. for your case json. Also you have to change the type of ActuaryId int to string in your model class. below is the working code.

 $.ajax({
        type: "POST",
        contentType: 'application/json',
        url: "api/url",
        data: JSON.stringify(courseAttended),
        success:  (response)=> {
            console.log(response);
        },
        error: (response) =>{
            console.log(response);
        }
    });

public class CourseModel
{
    public string ActuaryId { get; set; }

    public string Title { get; set; }

    public bool IsDone { get; set; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.