The issue of receiving a 404 error when attempting to send a string via Ajax

When a key is pressed and released, a JavaScript function is triggered. The function is supposed to call a controller action and return a result, but instead, I am receiving a 404 error. I have set breakpoints at the beginning of the controller action, but they are never triggered. I suspect that the issue lies in the type of request being made or in the data being sent along with it.
The code is written in C# MVC .NET 6

Java Script::::
function GetThingsContaining() { 

    $.ajax({
        type: "POST",
        url: "GetThingsContaining/MyController",
        data: { searchCriteria: "afd" },
        dataType: "json",
        success: function (data) {
            //do work if successful
        },
        error: function (data) {
            alert("Well that stinks")
        },
    }); 
}
   Controller Action
        [HttpPost]
        public IActionResult GetThingsContaining(string searchCriteria) {
            return PartialView("~/Views/Investments/_SearchDataList.cshtml", returnModel);
        }

Even though I have set a breakpoint at the return statement, it is never reached. The browser's dev tools indicate a 404 error.

Answer №1

Give this a shot: try implementing [FromBody] in the controller, then make a request in this manner

fetch('/MyController/RetrieveItemsContaining', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ searchQuery: 'abc' }),
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not successful');
        }
        return response.json();
    })
    .then(data => {
        // take action upon successful response
    })

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

Evaluating the generated HTML using JavaScript and Selenium testing

I am a new user of Selenium using C# and I want to automate the login process on a third-party website. When I manually navigate to the page in Chrome and inspect the elements, I can see the text boxes for username and password. <input type="text" id=" ...

Issues with displaying images in CSS when using HTML 5 canvas drawing

In attempting to draw an image on a canvas using a pre-loaded image and CSS, such as: img.style.backgroundColor="red"; ctx.drawImage(img,0,0,100,100); I have observed that the image is drawn without incorporating the CSS modifications. Are HTML canvases ...

Utilizing AJAX with a combination of JSON and HTML data types

I recently completed a tutorial on ajax and implemented a script that retrieves JSON data and appends it to a table. $.ajax({ url: 'insert.php', type: 'POST', data: {data1: name, data2: phone, data3: address}, dataTyp ...

The method Object.keys.map does not return the initial keys as they were in the original object

I'm retrieving an object from my database and it looks like this: {availability: null bio: null category: "" createdAt: "2020-10-13T13:47:29.495Z" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

Adding a div to the preceding div based on matching IDs in AngularJS

Here is a representation of my layout in HTML: <div ng-repeat="message in messages"> <div ng-class="{'messages messages--sent': userId == message.id, 'messages messages--received': userId != me ...

What is the best way to implement autoplay sound on a JavaScript webpage?

I'm currently working on a web system aimed at monitoring values from a database, and I have the requirement to trigger a sound alert when a specific range of values is received. Despite trying various examples found online, none of them have been suc ...

Displaying an array of JSON objects in ReactJS by parsing them

Recently, I've encountered an odd issue with my React App. I am attempting to parse a JSON object that includes arrays of data. The structure of the data looks something like this: {"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Ti ...

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...

Can anyone suggest a simple solution to make the MySQL Update statement function properly in C# code?

Hey there! I'm having some trouble with the Mysql Update Statement. I've tried everything I can think of, but it's just not cooperating. Oddly enough, the same mysqlconnection worked perfectly fine for Select and Insert Data. I even double ...

How can a pop-up be positioned to appear in the right bottom corner using jQuery

Is there a way to position a pop-up at the bottom right corner of the window? I have code that centers the pop-up in the window, but I'm looking to place it specifically at the bottom right corner. $(id).css('top', winH - $(id).height()); ...

Can you explain the significance of this code snippet 'true <=> false'?

Today I came across this piece of code: true <=> false. I'm a bit confused by it and don't really understand how it works. If anyone could shed some light on this expression for me, I would greatly appreciate it. For reference, this code ...

Guidelines on executing a function after page load in meteor

Currently, I am using cursor.observeChanges to monitor new records inserted in MongoDB and trigger a notification when that happens. The issue I am facing is that these notifications are popping up when my app is loaded for the first time or when I navigat ...

Retrieve the server code periodically and automatically refresh the form elements

Let's kick things off by explaining how the application functions: (please note there are multiple users on the page such as Patient M, Patient E, and so forth) 1) Check In: Next to Patient X's name, you will find a button labeled Check In. This ...

When trying to deserialize Json back into a list or enums, removing an enum item may lead to an error

Let's say I define the following enum: public enum Options { Choice1 = 1, Choice2 = 2, Choice3 = 3 } I populate a list with all these enum values using JsonConvert.SerializeObject. This results in a JSON string like this: ["Choice1","Ch ...

Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} I attempted to assign data.law to a variable, but received a typeer ...

Output the Partial View as a string within a Bootstrap Modal

Is there anyone who can help me? I am facing an issue with my View and Partial View (to be loaded in a Bootstrap modal). When I try to convert my partial view to a string, so it can be returned to my view, it comes back empty. However, if I add some tags ...

The AJAX POST function is not functioning properly when clicking on contextmenus

Can someone please assist me? I am having trouble sending data via ajax post to my nodejs server from contextmenus. It is not functioning as expected. Although the ajax request does not give any error alert, the data is not being sent successfully. I hav ...

Discover the power of utilizing the reduce function to extract the value of a specific field within an array of Objects

In the following example, we have an object with 3 forms: formA, formB, and formC. Form A and B are objects, while formC is an array of objects that can contain multiple items. const object: { "formA": { "details": {}, ...

What is the best way to ensure that navigation takes up the full width of the screen in pixels when

Trying to use jQuery to set a specific pixel width for my Bootstrap navbar that spans the entire width of the browser window. However, encountering some bugs as the width needs to be recalculated whenever the browser is resized. Currently, I have this cod ...

Version 4.6.4 of TypeScript is flagging the code as invalid

How can I fix this Typescript problem? const userInformation: { email: string; id: string; _token: string; _tokenExpirationDate: string; } = JSON.parse(localStorage.getItem('userData')); https://i.sstatic.net/xMh9P.pn ...