Search code examples
c#asp.net-mvc-4knockout.jsasp.net-ajax

Knockout AJAX data sent to C# controller is null


I'm trying to post a list of colors (id numbers) to a test function in my controller. I know the data is being sent and looks like it's formed correctly.

When I send the data fiddler shows this:

[{"ID":"15","Duration":"Permanent","bNotPermanent":"1"},   
{"ID":"21","Duration":"Permanent","bNotPermanent":"1"}]

Knockout AJAX post:

        SendData = ko.toJSON(self.AddColors) ;
        alert(SendData);

        $.ajax({
            ContentType: 'application/json; charset=utf-8',
            dataType: "json",
            type: "POST",
            url: '/EditColor/PostColors',
            data: SendData
        }).success(function (data) {

        });

The data class I'm using:

public class AjaxColorList
{
    public string ID { get; set; }
    public string Duration { get; set; }
    public string bNotPermanent { get; set; }
}

The controller function: (I also tried public JsonResult PostColors(String AddColors just to see if anything would come through)

    public JsonResult PostColors(List<Helpers.AjaxColorList> AddColors)
    {
        var ColorList = AddColors;  // breakpoint set here
        ....
    }

At the breakpoint in the function above I see that AddColors is null. I made sure the fields in the JSON query match what's in the data class. What am I missing?

I also changed the code so that it's passing only one object to the controller to verify that it can receive something... anything.

The added controller function looks like this:

    public JsonResult RequestAddColor(Helpers.AjaxColor AddColor)
    {
        var color = AddColor; // breakpoint here


         ...
    }

Fiddler shows this:

{"ID":"11","Duration":"Permanent","bNotPermanent":"false"}

But the controller shows all vars as null.

This has got to be something stupid / simple that I'm missing. Can anyone see the error in my logic?


Solution

  • Try this format for your ajax call, I recreated the scenario and this is working for me:

              $.ajax({
                    url: '/Home/PostColors',
                    contentType: "application/json",
                    async: true,
                    type: "POST",
                    data: JSON.stringify(sendData),
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log("FAIL: " + errorThrown);
                    },
                    success: function (data, textStatus, jqXHR) {
                        console.log("SUCCES");
                    }
                });