Sending data to the server using the $.post method with an

I am having some trouble creating a post using a customized model:

public class CallbackPriorityItemModel
{
    public int userID { get; set; }
    public int order { get; set; }
    public string name { get; set; }
}

Unfortunately, I can't seem to make this work. Here is the code I have:

function updateUserCallbackList() {
    var cbList = [];
    $(".callbackListItem").each(function () {
        cbList.push({
            Name: this.id,
            Order: $('li').index(this.parentElement),
            UserId: _userID
        });
    });
    var args = {
        CbList: cbList,
        UserID: _userID
    };
    $.post(SiteUtil.urlContent('/api/AccountApi/UpdateCallbackPriorityList?' +   $.param(args)));
}

This code calls the following method:

[HttpPost]
public void UpdateCallbackPriorityList(CallbackPriorityItemModel[] cbList, int userID)

I have verified that cbList is not null in the javascript, but it always appears as null when it reaches UpdateCalbackPriorityList, even though userID is not null. I have also attempted using other methods:

var url = SiteUtil.urlContent('/api/AccountApi/UpdateCallbackPriorityList/');
 $.ajax({
     url: url,
     type: 'POST',
     data: JSON.stringify(args),
     dataType: 'json',
     contentType: 'application/json; charset=utf-8'
 });

However, I receive errors stating that the browser could not locate UpdateCallbackPriorityList. Any suggestions?

;

Answer №1

Here is an example you can use:

$.ajax({
    url: SiteUtil.urlContent('/api/AccountApi/UpdateCallbackPriorityList'),
    type: 'POST',
    data: args,
    contentType: 'application/json; charset=utf-8'
});

Modern versions of jQuery will automatically serialize objects when passed into the $.ajax data parameters.

In addition, make sure to match the capitalization in your JavaScript variable names with C# - ASP may adjust for this but it's worth seeing if aligning them helps.

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

Develop objects with a fixed position - three.js

I am currently working on a game utilizing the three.js library and I have a specific requirement. I would like to incorporate a small "panel" on the screen that remains stationary regardless of the user's navigation through the 3D environment. Essent ...

Creating a CSS full-width navigation menu

Recently, I came across a menu code on the web that seemed great. However, I wanted to make my menu responsive and full width. Since I am new to CSS and HTML, adjusting the menu code has been a bit of a challenge for me. .menu, .menu ul { list-style: ...

Is it possible for a Safari extension to store cookies?

Can Safari extensions store cookies locally instead of relying on the browser's cookies? I'm getting annoyed with the login popup appearing during HTTPS ajax requests. I have experience logging into Google services through curl and perl/php scrip ...

Is it feasible to arrange <DIV>s based on their dates?

I encountered an issue while working with an ordering function. var $wrapper = $('#list'); $wrapper.find('.blogboxes').sort(function (a, b) { return +b.dataset.date - +a.dataset.date; }) .appendTo( $wrapper ); <script src="ht ...

The key to successful filtering in Next.js with Hasura is timing - it's always a step

I am fetching data from Hasura using useRecipe_Filter and passing the searchFilter state as a variable. It seems that every time I press a key, the UI updates with one keystroke delay before filtered data is passed to the results state. const SearchBar = ( ...

When attempting to change an image using JavaScript, the image fails to load

I am having trouble understanding what is wrong with my code. <html> <body> <script type="text/javascript"> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { ...

Cease the clicking action event

How do I terminate a mousedown function when the mouse is released? $('#manRun').mousedown(function(e3) { var manID = get_id(this); e3.preventDefault(); $(document).on('mousemove.moveMan', function(e2) { ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

Access the CSV file using Office365 Excel via a scripting tool

Objective I want to open a CSV file using Office365's Excel without actually saving the file on the client's machine. Challenge The issue with saving raw data on the client's machine is that it leads to clutter with old Excel files accumu ...

Sending an ArrayBuffer from Angular to Electron results in the window crashing

In my Electron application, I have integrated an Angular application internally. I am trying to download a byte array (ArrayBuffer) via an API call and then passing this data to a method connected through electron.remote.require('./file-service') ...

Identifying Mistakes to Address Promise Failures

I encountered unhandled promise rejection errors and attempted to catch them and log them after each .then statement. Unfortunately, I ran into an 'unexpected token' issue when running the code on my server due to the period before .try. Despit ...

Add the teams-js library to your Vue.js project

I'm currently working on integrating the Microsoft Teams SDK into my Vue.js project. After installing the npm package and referencing it in my vue-file, I noticed that the microsoftTeams alias is displaying as undefined. Is there a step I may have ove ...

Struggling to concentrate on a text field following navigation in an AngularJS application

My current project involves working with an AngularJS application where I am facing a challenge in setting the cursor or focus on a specific text box when routing to a page. Despite my attempts using various methods such as setFocus() in JavaScript, autofo ...

Refresh a page in AngularJS with only a single click

I am currently working with angularjs and I am trying to figure out how to refresh the page only once when it loads. Here is what I have attempted so far: <script> app.cp.register('userProfileController', function ($window) { debugger; ...

Are the fetch functions within getStaticProps and getServerSideProps equivalent to the fetch API native to web browsers?

I've been working with Next.js for some time now and I'm questioning the fetch API used in both getStaticProps and getServerSideProps. Below is my understanding of these functions: getStaticProps runs during build time and ISR getServerSidePro ...

Adding an item to a JSON array in Angular

I'm having trouble adding a new item to the roleList JSON array. I've tried using push/concat, but it doesn't seem to update the roleList array. Any suggestions on how to resolve this? // The javascript : function RoleListCtrl($scope) { ...

Applying a CSS class (or style) dynamically depending on the variable with the help of a directive

I'm facing a situation where I need to apply ng-style (or ng-class) multiple times depending on a variable. However, this repetitive task of writing ng-class for the same functionality for each widget is quite cumbersome for me. Is there a way to si ...

Refresh all fields for various products with a single click of a button

Our Magento multi-vendor site allows vendors to easily manage their products. For each single product, vendors can view and update information such as price, selling price, quantity, and more from their vendor account. We have implemented a feature where ...

Although everything appears to be running smoothly in Express, my request is returning null

I am facing an issue with a router in my code. In the main index.ts file, I have the following line: app.use("/api/tshirts", tshirts) And in tshirts.ts file, I have defined the following routes: router.get("/", tshirtsController.getTShirts) router.get("/ ...