Using Jquery.Ajax to send a pair of arguments to a POST api请求

My controller method has the following structure:

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

In this method, a user can save a set of changerequests along with adding a comment. The ajax call is constructed like so:

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

The current ajax call does not include the comment parameter. How can I modify it to include the comment as an argument?

Answer №1

How 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("Data Saved Successfully!");
    successCallback();
}

Although I'm not well-versed in KO, I presume it would function on the same premise:

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

Answer №2

Another option is to send a POST request with a single object structured like this:

{
ChangeRequest[] changeRequests;
string comment;
}

Answer №3

Although Marcus provided a helpful answer that was almost there, I made some tweaks to it that ultimately worked better:

//comment() is an observable in knockout that is passed in when this function 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)
        {
            // do something
        }

Afterwards, I created a model to convert the json object into a usable C# object:

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

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

        public string Comment { get; set; }
    }
}

Big thanks to Marcus for getting me started on this solution!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The bootstrap datepicker does not display the date range on the calendar

I tried to incorporate a bootstrap datepicker date-range in the code snippet below, but I am encountering an issue where the selected date range is not displaying on the calendar. <!DOCTYPE html> <html> <head> <link rel="stylesheet" ...

Storing JSON data in a concealed field and extracting it for use in a function

I have a function that retrieves the number of rows from a database table using JSON in my application. function getRowCount() { $.ajax({ headers: { 'Accept': 'application/json', 'Conte ...

What is preventing me from using jQuery to dynamically insert HTML onto the page?

Below is the HTML code for a Bootstrap Modal dialog box: <div class="modal fade" id="rebateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> ...

Pass JavaScript variables to a PHP file with the help of AJAX

Hey there, I'm new to developing web-based applications and currently learning about AJAX. I've run into a problem while trying to make an AJAX request with user inputs as variables and fetching the same variables in a PHP file. Below is the code ...

Modify the text or background shade of the Bootstrap date picker

I have successfully integrated the bootstrap date picker (view figure below) and it is functioning as expected. The code appears like this: <div class="input-group date"> <input name="departure" type="text" class="form-control" id="departure" ...

Creating a unique, random output while maintaining a log of previous results

While working on a recent project, I found myself in need of a custom Javascript function that could generate random numbers within a specified range without any repetitions until all possibilities were exhausted. Since such a function didn't already ...

Having trouble establishing a connection to the remote server using node js?

I have been working on integrating a third-party Recharge API. I provided them with the necessary URL, so that whenever a message is sent - whether it's a success or failure - they can update the URL accordingly. Upon checking my AWS system, everythi ...

Is it possible that .focus() does not function on a duplicated object?

Greetings to all! I have created a form with rows of input text fields. Users can add as many rows as needed by clicking the 'add row' button. The functionality to clone() for adding rows is working perfectly. In each row, an input field can o ...

Error: Unforeseen symbol detected in JSON data

After receiving a JSON object from my server, I attempted to parse it using the jQuery function. However, upon running var response = jQuery.parseJSON(data), an error was thrown: {"Success":0,"ex":"The system cannot find the file specified"} The error me ...

`Trigger a page reload when redirecting`

Currently, I am tackling some bug fixes on an older Zend Framework 1.10 project and encountering difficulties with redirection and page refresh. The issue: The task at hand is to make an AJAX call, verify if a person has insurance assigned, and prevent de ...

Issue with Ajax-Enabled WCF Service (JSON) encountered during utilization with jquery .ajax()

Regrettably, the error condition is only triggered when calling .ajax(), and textStatus (the second parameter) merely displays "error". Despite thoroughly examining multiple examples and other inquiries on stackoverflow, I seem to be overlooking something ...

What is the reason for needing a page reload in Javascript or JQuery?

I'm curious why Javascript or jQuery require a page reload before applying certain effects. CSS updates in real-time, as demonstrated by the following example: This changes dynamically without needing to refresh the page @media all and (max-width:7 ...

What is the method for switching on and off responses for initial level comments?

Is there a way to manage long comments and replies on my website's nested comment system? I attempted to Hide/Toggle replies upon page load using Ajax, but it was unsuccessful. I added an id to the child comments container and used code to achieve th ...

The iPhone header position switches when an HTML5 input type number is selected

I am currently working on a project that involves jQuery Mobile and PhoneGap. One issue I am encountering is when using the iPhone version, the header position changes when I click on an input type number. NOTE: When I focus on the input type number in my ...

A: Looking to implement form validation with Ajax in CodeIgniter?

Hey there, I am currently trying to implement form validation in CodeIgniter using Ajax on the server side, but I am facing some issues. My goal is to display an error message with 'required' under the form input fields when necessary. Could some ...

What is the best way to hide a custom contextmenu in AngularJs?

I created a custom contextmenu directive using AngularJs. However, I am facing an issue where the menu is supposed to close when I click anywhere on the page except for the custom menu itself. Although I have added a click function to the document to achie ...

Exploring collapsible data tables in Angular with Bootstrap styling

I am attempting to transform my static bootstrap data table, which displays the total count of fruits harvested in various months in an incremental manner, into a dynamic one using the JSON provided below: JSON { "fruit": [ { "fruitName": "Al ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Increase the value of a number using jQuery

When using jquery to animate a random number increment from 0001 to 1000, the issue arises when reaching the number 0077. The final number displayed is 77 instead of 0077. Is there a solution to ensure the format remains as 0077? Your help is appreciated. ...

Exploring techniques for retrieving hyperlinks from table cells using Selenium in C#

<tr role="row" class="odd"> <td class="sorting_1">Abrar</td> <td>1571</td> <td>Out</td> <td>No</td> <td>ALL</td> <td>Deskflex</td> <td> <a ...