Jquery.Ajax向POST api发送两个参数

时间:2014-08-05 14:30:57

标签: c# jquery ajax asp.net-mvc controller

我有一个看起来有点像这样的控制器方法:

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

用户可以保存一组更改请求并添加注释。 ajax调用看起来有点像这样:

$.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();
        }

请注意,在此ajax调用中,我没有包含注释。使用此,如何将注释作为ajax调用的参数包含在内?

3 个答案:

答案 0 :(得分:2)

这个怎么样?

$.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();
}

我没有KO的经验,但我认为它可以使用相同的原理:

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

答案 1 :(得分:1)

您还可以以以下形式回复单个对象:

{
ChangeRequest[] changeRequests;
string comment;
}

答案 2 :(得分:0)

马库斯的回答非常接近最终的工作,但这是它的延伸:

//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
        }

然后,我必须创建一个模型,将json对象转换为我可以在C#中使用的对象

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

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

        public string Comment { get; set; }
    }
}

感谢Marcus的开始!