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; }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Tiisetso Tjabane
  • 2,088
  • 2
  • 19
  • 24

2 Answers2

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.

Tiisetso Tjabane
  • 2,088
  • 2
  • 19
  • 24
  • 2
    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. – Nkosi Oct 22 '18 at 09:47
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; }
}
R.Sarkar
  • 344
  • 2
  • 8