$ .ajax post, knockout and web api

I have a method in my web api controller that is 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 breakpoint in the controller and it hits. Omitted in a template variable, all attributes are always zero, and the question is - why? I'm not sure what to pass in the $ .ajax call, the data parameter.

In javascript, I have this (below). In the data property, I tried it myself, this, ko.JS, ko.JSON - each with self, this, $ data, $ root as input, and it seems like I didn't put anything in there, passes the value. In aspx, I have a textarea with data-bind = "value: ko.toJSON ($ root)" and it contains 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;
}

      

+3


source to share


1 answer


I believe you need to specify the dataType as json. The following works for me (with node / express as a 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");
      }
    }
...

      

0


source







All Articles