Abarnett
Abarnett

Reputation: 327

Jquery.Ajax sending two arguments to POST api

I have a controller method that looks a bit like this:

[HttpPost]
        public HttpResponseMessage SaveFunc(ChangeRequest[] changeRequests, string comment)
        {
            //do stuff
        }

Where a user is able to save a set of changerequests and add a comment. The ajax call looks a bit like this:

$.ajax({
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        url: Constants.appRoot + "/api/myapi/SaveFunc",
        type: "POST",
        data: ko.toJSON(self.changeRequests),
        success: function (response) {
            self.message("Saved!");
            successCallback();
        }

Note that in this ajax call, I have NOT included the comment. Using this, how can I include the comment as an argument of the ajax call?

Upvotes: 2

Views: 98

Answers (3)

Abarnett
Abarnett

Reputation: 327

Marcus's answer is very close to what ended up working, but here's an extension of it that worked out:

//comment() is a knockout observable passed in when this func is called

$.ajax({
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            url: Constants.appRoot + "/api/myapi/save",
            type: "POST",
            data: JSON.stringify({ changeRequests: ko.toJS(self.changeRequests), comment: comment()}),
            success: function (response) {
                //.......
            }

//api method
[HttpPost]
        public HttpResponseMessage Save(ChangeSet changeSet)
        {
            //dostuff
        }

then, i had to create a model that would turn the json object into an object i can use within the C#

//model
namespace Web.Models
{
    using Application.Models;

    public class ChangeSet
    {
        public UserChangeRequest[] ChangeRequests { get; set; }

        public string Comment { get; set; }
    }
}

Thanks for the start Marcus!

Upvotes: 0

user2202911
user2202911

Reputation: 3014

You could also POST back a single object in the shape of:

{
ChangeRequest[] changeRequests;
string comment;
}

Upvotes: 1

Marcus
Marcus

Reputation: 8669

What about this?

$.ajax({
dataType: "json",
contentType: "application/json;charset=utf-8",
url: Constants.appRoot + "/api/myapi/SaveFunc",
type: "POST",
data: JSON.stringify({changeRequest: self.changeRequests, comment: "mycomment"}),
success: function (response) {
    self.message("Saved!");
    successCallback();
}

I have no experience of KO, but I assume it would work using the same principle:

data: ko.toJSON({changeRequest: self.changeRequests, comment: "mycomment"}),

Upvotes: 2

Related Questions