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:

Request Body:

Output:

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:

Request Body:

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

The AngularJS framework is failing to disable the autocomplete feature for the input field with a password type

I have attempted to disable auto-complete for the password input, but it doesn't seem to be working. Below is a sample of my code: <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off"> <input type="password" id="passwor ...

Creating a personalized .hasError condition in Angular 4

I am currently in the process of modifying an html form that previously had mandatory fields to now have optional fields. Previously, the validation for these fields used .hasError('required') which would disable the submit button by triggering a ...

Creating a template based on an object type in JavaScript with Angular: A step-by-step guide

I have a collection of objects, each with a property indicating its type. Here's an example: [ { "type" : "date", ... },{ "type" : "phone", ... },{ "type" : "boolean", ... } ] I'm ...

How to retrieve the chosen option from a drop-down menu in WebDriver using JavaScript without relying on the Select Class

Currently, I am in the process of utilizing Webdriver with Java. My goal is to retrieve the selected value from a combobox without relying on the Select class provided by Webdriver. The specific markup that I am dealing with is as follows: <select nam ...

Click on the link to open it in a SharePoint modal and populate it with the value from the

After populating a ng-grid with SharePoint items, my goal is to have the SharePoint edit form open in a modal window when the edit button at the end of each row is clicked. However, I am encountering difficulties when using OpenPopUpPage as the {{row.entit ...

How to fetch files using URL in JavaScript

I need a solution for automatically downloading multiple PDF files from Google Drive and Docs using their URLs with JavaScript code. I don't want to manually go to each link to download the files. Although I've researched various answers on Stac ...

I can't seem to figure out why I keep encountering a runtime error whenever I attempt to create a basic route in the latest version of nextjs, version 13.5

Encountering an error while attempting to create a basic route in app/dashboard/page.tsx. The error message suggests that the contents are not a valid react component, even though they conform to valid react component syntax. Unhandled Runtime Error Erro ...

Updating ng-model with the values from a property in a collection in AngularJS

Encountering an unusual problem with setting the ng-model for a select drop-down menu. Despite using a property value that matches one in the ng-options, the ng-model consistently ends up as null. Below is the function responsible for fetching orders: o ...

Guide on utilizing JSON data sent through Express res.render in a public JavaScript file

Thank you in advance for your assistance. I have a question that has been on my mind and it seems quite straightforward. When making an app.get request, I am fetching data from an external API using Express, and then sending both the JSON data and a Jade ...

Console log displays varied outputs for identical arrays

Having an array in a static form and one that is filled using the ajax post function, I initially planned to replace the static array with the dynamic one. However, upon closer inspection, it seems that the two arrays are not matching. Array 1 (static) ...

Creating an alarm clock with customizable time and date formats using ReactJS with Material-UI integration

Here is the code I have written: const date = new Date(); const currentTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; const getDay = `${date.getDay()} ${date.getMonth()} ${date.getDate()}`; return ( <Box> < ...

Transform a 3D text rotation JavaScript file into an Angular component tailored TypeScript file

I have a javascript file that rotates text in 3D format, and I need help converting it into an Angular component specific TypeScript file. You can find the codepen for the original JavaScript code here. Below are my Angular files: index.html <!doctyp ...

Utilizing a third-party API within the next/api endpoint

I've recently started working with NEXTJS and developed a weather application. I'm integrating the openweather API, but I'm unsure how to use it within the next/api. I attempted creating a file named today.js inside the next/api directory an ...

The spotlight is shifting towards validating a datepicker field using jQuery

I am currently working on validating a datepicker field using jQuery. However, whenever I try to validate it, the calendar popup opens up. I only want to display the validation message without the datepicker popup. ...

Issue with jQuery week calendar: Existing data not loading correctly into the calendar

I am currently experimenting with the jQuery week calendar plugin found at https://github.com/themouette/jquery-week-calendar/wiki in order to showcase meetings on my website. However, I am encountering an issue where my events.php file is returning JSON d ...

Is it possible to utilize the addition assignment operator (`+=`) to modify the `transform:rotate('x'deg);` CSS property using

This is the code I have been working on: #move{ height:70px; width:70px; border:2px solid black; border-radius:15px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="button" val ...

Switch out the arrow icon in the dropdown menu with an SVG graphic

Looking for a way to customize the dropdown caret in a semantic-ui-react component? Here's how it currently appears: <Dropdown className="hello-dropdown" placeholder="Comapany" onChange={this.someFunction} options={som ...

Mootools powerfully handles form submissions

Looking for advice on securely sending a registration form via Ajax Post (using Mootools) to a PHP file. What's the best approach? Thank you! ...

How to execute a system command or external command in Node.js

I am encountering an issue with Node.js. When using Python, I would typically perform an external command execution like this: import subprocess subprocess.call("bower init", shell=True) Although I have explored child_process.exec and spawn in Node.js, I ...

Building a Mongoose Schema with an Array of Object IDs: A Step-by-Step Guide

I created a user schema using mongoose: var userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true}, password: { type: String, required: true}, name: { first: { type: String, required: true, trim ...