What is the best way to send data to an API controller using AJAX in an MVC framework?

I am facing an issue with POSTing a string data to the api controller in mvc using ajax. Despite my efforts, the data does not seem to reach the api controller. Here is what I have attempted:

This is the JavaScript code I have used:

        
        jQuery(function () {
            $(function () {
                $(".listing-listing").html("");
                
                const jsonData = { PageNom: 1, ShowInPage: 25 };
                var data = JSON.stringify(jsonData);
                
                $.ajax({
                    url: '/Api/apiListProduct/AjaxSearchAsync',
                    type: 'POST',
                    data: data,
                    dataType: 'jsonResult',
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        if (result.Data.Succeed) {
                            result.Data.ProductLst.forEach((product) => AddProduct(product));
                            //$('.PaginationCell').html(result.Data.Pagination);
                        }
                    },
                    error: function (e) {
                        // handle error
                    }
                });
            });
        });
    

And here is the corresponding api controller:


        public class apiListProduct : ApiController {
            [System.Web.Http.HttpPost]
            public async System.Threading.Tasks.Task<System.Web.Mvc.JsonResult> AjaxSearchAsync()
            {
                string raw = "";
                using (var contentStream = await Request.Content.ReadAsStreamAsync())
                {
                    contentStream.Seek(0, System.IO.SeekOrigin.Begin);
                    
                    using (var sr = new System.IO.StreamReader(contentStream))
                    {
                        raw = sr.ReadToEnd();
                    }
                }
            }
        }
    

Your assistance in resolving this issue with the web API route for the api controller will be greatly appreciated. Thank you.

Answer №1

I am facing an issue with posting string data to an API controller in MVC using Ajax. Despite my attempts, the data does not reach the API controller. How can I successfully send data to the API controller through Ajax in MVC?

Based on your explanation and code snippet, it would be helpful if you provide the complete API controller code and specify the version of ASP.NET Core you are using.

After reviewing your code, I have identified two potential problems.

Firstly, the definition of your API route is crucial for this process to work correctly.

Another issue lies in the usage of

Request.Content.ReadAsStreamAsync
. Instead of this, try reading the request body content using HttpContext.Request.Body, as it accesses the request body Stream.

To resolve this problem, I suggest trying the following approach that has been successful:

Here is a practical example of how you can send your Ajax request to the API controller:

API Controller:

[Route("api/[controller]")]
[ApiController]
public class ApiListProductController : ControllerBase
{
    [HttpPost]
    [Route("AjaxSearchAsync")]
    public async Task<IActionResult> AjaxSearchAsync()
    {
        string raw = "";
        using (var contentStream = HttpContext.Request.Body)
        {
            using (var sr = new System.IO.StreamReader(contentStream))
            {
                raw = await sr.ReadToEndAsync();
            }
        }
        return Ok(raw);
    }
}

Note: If your API project and MVC project are separate, you can remove the route annotation

[Route("AjaxSearchAsync")]
. However, if they are within the same project, use an explicit route. Please refer to route details here.

Request Payload:

https://i.sstatic.net/pKZSf.png

Request Body:

https://i.sstatic.net/zeBYo.png

Output:

https://i.sstatic.net/yBKBn.gif

Alternatively, you can use a strongly-typed model to retrieve the parameters posted from the Ajax request. Here is an example of such a model:

public class SearchModel
{
    public int PageNumber { get; set; }
    public int ItemsPerPage { get; set; }
}

Controller:

[HttpPost]
[Route("AjaxSearchAsyncApproachTwo")]
public async Task<IActionResult> AjaxSearchAsyncApproachTwo(SearchModel searchModel)
{

    return Ok(searchModel);
}

Request Payload:

https://i.sstatic.net/w3uI0.png

Request Body:

https://i.sstatic.net/o57zI.png

Note: Based on my test, your JavaScript/jQuery code appears to be correct. You can choose either of the above methods to read the request body or request parameters. Additionally, please refer to this official document for more information.

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

v-for loop to populate dropdown menu with identical values

Recently, I started working on a points counter app using Vue.js and encountered some issues with the v-for loop and dropdown menu functionality. Within my Vue.js application, I have an array of players as shown below: var app = new Vue({ el: '#l ...

Explanation of timespan format in .net 4.5 standard serializer

I am facing an issue with deserializing a TimeSpan property in my object using both .NET serializer and Newtonsoft.Json. In my MVC Action, the timeSpan prop is being deserialized as follows: "EndTime":{"Hours":9,"Minutes":0,"Seconds":0,"Milliseconds":0,"T ...

What's causing this javascript to malfunction on the browser?

I encountered a problem with the code in my .js file. Here is a snippet of the code: $.extend(KhanUtil, { // This function takes a number and returns its sign customSign: function(num){ num = parseFloat(num) if (num>=0){return 1} ...

The JS Fiddle code fails to function properly once it has been downloaded to the local computer

I came across a helpful example fiddle webpage: jsfiddle.net/yijiang/6FLsM/2 After following examples from others, I attempted to download (right click and Save As) using the latest Chrome browser with the following links: jsfiddle.net/yijiang/6FLsM/2/s ...

Stop the stream coming from getUserMedia

After successfully channeling the stream from getUserMedia to a <video> element on the HTML page, I am able to view the video in that element. However, I have encountered an issue where if I pause the video using the controls on the video element a ...

Dealing with Jquery scope problems when using $.post

I've encountered a minor issue with my code. I am making a POST request to my page, and after it should return "OK" to indicate success. Within my handler function, I use set_var(data) to update my global variable text. However, the problem arises whe ...

Exploring Three.js: The challenge of loading multiple material objects

I am currently using three.js and facing an issue while loading multiple material objects. The problem arises when I rotate the code, causing unexpected behavior with the second material object. Ideally, I want the first material object [cubeMaterial] to r ...

Guide to scraping a website using node.js, ASP, and AJAX

I am currently facing an issue where I need to perform web scraping on this specific webpage form. This webpage is dedicated to vehicle technical reviews, and you can try inputting the car license CDSR70 for testing purposes. As mentioned earlier, I am u ...

Converting a datatable into a list of webelements in C# - a step-by-step guide

Exploring C# and utilizing specflow for automation I am currently working on a scenario that involves checking the enabled status of multiple elements. These elements are located in different parts of the page and have unique xpaths. My planned approach ...

The previous and next arrows do not have a looping feature

I have a collection of 10 HTML pages stored in a folder called PROJECTS. Everything is functioning properly, except for the prev and next arrow navigation buttons. The issue arises when navigating to the last page (e.g., projectPage_10.html) from my Projec ...

What is the process for uploading a file using the client's file path?

I'm fascinated by the way Sonic Living is able to identify and upload your iTunes library XML file with such ease. Unlike other upload libraries I've explored, it prompts user approval before automatically uploading the XML file based on client O ...

I am experiencing unexpected results with my Mongoose filter and sort query in Express JS middleware. The output does not match what I am anticipating, and the sorting functionality seems to

This middleware is used for filtering and sorting data. I made some modifications to it, but it's not functioning as expected: const aliasTopMenu = (req, res, next) => { req.query.sort = '-price'; req.query.fields = 'name,price, ...

Discovering the final step of a for loop when working with JavaScript objects

Currently, my data consists of: {12: Object, 13: Object, 14: Object} I need help figuring out how to detect the final iteration in the for loop below: for (var i in objs){ console.log(objs[i]); } Does anyone have any solutions? ...

Using Rails: How to invoke a function in the asset pipeline from a JS response?

In one of the JavaScript files I am working with, I have defined an object and a function: chosen.coffee Foo = do_this: -> $('.slider').slider() $ -> Foo.do_this() This code initializes JQueryUI to turn a specific div into a ...

Rotate images using a JQuery plugin without using HTML tags, solely through passing the images in JavaScript

I am currently working on creating a jQuery image rotator from scratch. While I know there are simple jQuery sliders/rotators available, I specifically want to include the image files directly within the JS code. I do not want to use this HTML structure: ...

Python Tornado JSON request handling

When my application receives data from the POST method using JQuery's AJAX request, it is sent in JSON format. However, when I try to access the data in the handler, it appears as a byte string type. To retrieve the data, I am using the my_body = sel ...

What can be done to stop $.ajax from automatically appending [] to my key names when making requests (aside from using processData: false

When attempting to utilize $.ajax for a POST request with data in the following format: { list: ["fake_id_0"], mapType: "fakeToRealId" } jQuery seems to alter the structure by adding brackets only to the key list, transforming it into: { lis ...

Check the Full Calendar to see if any events are scheduled for today

I have a group of users who need to save their availability. Currently, I am utilizing Full Calendar and looking for a way to prevent them from adding the same event multiple times on a single day. My tech stack includes VueJs and all events are stored in ...

Encountering Issues with Formatting InnerHtml Text using RegEx

Technology: React.js I have been working on a custom function in JavaScript to highlight specific words within a code block. The function seems to be functioning correctly, but the highlighting isn't staying after the function is completed. Any ideas ...

Browserify pulls in entire module even if only specific parts are utilized, such as react-addons

I am currently using Browserify to bundle my server-side react.js code for the client. There is a concern that utilizing a module from an npm package may result in the entire package being bundled by Browserify. Question: Will require('react-addons& ...