0

I want to update some records in database with single Ajax call but model has no elements in server side.

I tried to make a JSon object and pass it to an API controller via Ajax.

JQUERY:

        var JSONObject = { SortedAnswersViewModel: [] };
        var answer;
        var $listElements = $sortableList.children();

        var orderNumber = 1;
        $.each($listElements, function (i, v) {
            answer = { ID: parseInt(v.id), OrderNumber: orderNumber };
            orderNumber++;
            JSONObject.SortedAnswersViewModel.push(answer);
        });

        console.log(JSON.stringify(JSONObject)); // Here I can see JSON object correctly

        var ajaxRequest = $.ajax({
            type: "POST",
            url: "/api/Cloudition/EditAnswersOrder",
            data: JSON.stringify(JSONObject),
            success: function (data) {
              // Codes...
            },
            error: function (xhr, ajaxOptions, thrownError) {
              // Codes...
            }
        });

Model:

public class SortedAnswersViewModel
{
    public int ID { get; set; }
    public int OrderNumber { get; set; }
}

Controller:

    [HttpPost]
    public string EditAnswersOrder(List<SortedAnswersViewModel> model)
    {
        try
        {
            int i = 1;
            foreach (var item in model)
            {
                int answerID = Convert.ToInt32(item);
                AnswerStep answer = db.AnswerSteps.Where(ans => ans.ID == answerID).FirstOrDefault();
                answer.OrderNumber = i;
                i++;
            }
            db.SaveChanges();
            return "AnswersOrderEdited";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

All I have in controller is an empty list (count=0). Any solution? Actually is it possible?

Mehdi
  • 499
  • 1
  • 7
  • 31
  • I think this link is useful: https://stackoverflow.com/questions/13242414/passing-a-list-of-objects-into-an-mvc-controller-method-using-jquery-ajax – hassan.ef Jun 02 '19 at 12:15
  • @ hassan.ef , thanks it's almost what I've done, but the result's count is 0 yet. – Mehdi Jun 02 '19 at 12:42
  • 1
    Try to change the param name: *var JSONObject = { model: [] };* and add the next params to json-call: *contentType: 'application/json; charset=utf-8', dataType: 'json',*. – vladimir Jun 02 '19 at 18:15

1 Answers1

0

It may seem very trivial, but contentType makes all the difference in the HTTP pipeline, mainly because the undefined contentType uses the default contentType value option (that is "application/x-www-form-urlencoded"); in your case, where your Web API expects consumption in the client's JSON format, you need to configure the contentType: "application/json". Your ajax function will be like this:

var ajaxRequest = $.ajax({
        type: "POST",
        url: "/api/Cloudition/EditAnswersOrder",
        contentType: "application/json",
        data: JSON.stringify(JSONObject),
        success: function (data) {
          // Codes...
        },
        error: function (xhr, ajaxOptions, thrownError) {
          // Codes...
        }
    });
Antonio Leonardo
  • 1,805
  • 1
  • 8
  • 18