Question

I am unable to get my JSON to my controller, and I can't figure out why the value I get in javascript isn't being passed to the controller. Here is my ajax post in my javascript:

this.save = function () {
        var data = ko.toJSON(this.Routines);
        $.ajax({
            type: 'POST',
            url: "CreateJson",
            data: data,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (result) {
                if (!result.success)
                    alert("test")
                else { }
            }
        })
    }

now data contains

[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}] 

which is what I want, but the controller shows nothing. Here is my controller

[HttpPost]
    public JsonResult CreateJson(t_routine routine, string data)
    {

        var message = "success";
        return Json(message);
    }

As I understand it, MVC 3+ automatically receives JSON without any need for parameters like my string data, I just threw it in there to try and figure out if I'm getting anything at all. data is null and routine shows 0's and null for values. What am I missing?

Was it helpful?

Solution

If t_routine represents the server side type for

[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]

Then it might be enough to call JSON.stringify on the ko.toJSON result like this

this.save = function () {
    var data = JSON.stringify(ko.toJSON(this.Routines));
    $.ajax({
        type: 'POST',
        url: "CreateJson",
        data: data,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (!result.success)
                alert("test")
            else { }
        }
    })
}

the data parameter on your controller action is not needed then and you most likely need to change the t_routine parameter to t_routine[]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top