user1202839
user1202839

Reputation: 375

$.ajax post, knockout, and web api

I have a method in a web api controller that is being called from a javascript (knockout) function.

    public void SaveEmailTempage(EmailTemplateModel template)
    {
        var x = template.ToString();
    ...

the x variable above is only there so I can set a break point in the controller, and it gets hit. The passed in template variable has all of it's attributes always set to null and that is the question - why? I'm not sure what to pass in in the $.ajax call, data parameter.

In the javascript I have this (below). In the data property, I've tried self, this, ko.JS, ko.JSON - each with self, this, $data, $root as an input and it seems nothing I put there passes a value. In the aspx, I have a textarea with data-bind="value: ko.toJSON($root)" and it does contain the json that I would like to send to the server.

    function emailViewModel() {
    var self = this;
    //data
     ...   
    //operations
    ...
    self.saveTemplate = function () {
        $.ajax({
            url: '/api/emailtemplate/',
            type: 'POST',
            data: ko.toJSON({template: self}),
            contentType: 'application/json',
            success: function (result) {
                alert('success');//debug
            },
            error: function () { alert('fail');}//debug

        });
    }
    return self;
}

Upvotes: 3

Views: 3222

Answers (1)

7zark7
7zark7

Reputation: 10145

I believe you need to specify the dataType as json. The following works for me (with node/express as the POST handler):

...
this.saveTemplate = function() {
   $.ajax({
      url: "/api/emailtemplate",
      type: "POST",
      data: ko.toJSON({ template: this }),
      contentType: "application/json",
      dataType: "json",
      success: function(result) {
        alert("success");
      },
      error: function() {
        alert("fail");
      }
    }
...

Upvotes: 0

Related Questions