What is the process for invoking an MVC Api controller's Post action with a HttpResponseMessage using JavaScript as the client

Currently, I am making an API call from the client side. Below is the code snippet for both the client and server sides:

API Action in C#:

public class StudentTestController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage GetLessonInfo(int request)
        {
            HttpResponseMessage result = null;

            result = Request.CreateResponse(HttpStatusCode.OK,StudentTest.GetLessonInfo(request));

            return result;
        }
    }

JavaScript client script:

function SendRequest() {

        var url = "http://localhost:1938/api/StudentTest/GetLessonInfo";

        var data1 = "request=293";

        $.ajax({
            type: 'POST',
            url: url,
            data: data1,
            contentType: 'application/json; charset=utf-8',
            dataType: 'jsonp',
            success: function (data) {
                $('#txtResponce').val(JSON.stringify(data.Data));
            },
            error: function (xhr, status, error) {
                var errorText = xhr.status + "\r\n" + status + "\r\n" + error;
                $('#txtResponce').val(errorText);
            }
        });
    }

Even after implementing the above code, I faced an issue where the controller action was not being called. Does anyone know how to resolve this?

Answer №1

Krishna. Why not give this a shot instead:

let endpoint = "/api/StudentTest/GetLessonInfo";
let dataToSend = "293";

Perhaps if "request=293" is interpreted as a string rather than the expected integer parameter, it could be causing issues. Additionally, since the integer parameter cannot be null, it might result in a Bad Request error.

Use Fiddler to investigate what is being transmitted to the server.

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

Save all user-entered tags in one column of a database using Laravel 8

I've implemented a form that includes an input tag. <form id="filialeform" action="filiales" enctype="multipart/form-data"> {{ csrf_field() }} <input type="hidden" id="id_hidden" name=&quo ...

Is incorporating re-routing into an action a beneficial approach?

My main concern involves action design strategies: determining the best timing and method for invoking actions. In my project using Mantra (utilizing React for the front-end and Meteor's FlowRouter for routing), there is a UI component that includes ...

Rearrange elements within a div by clicking a button

I want to shuffle div elements with a click of a button using a dissolve animation in HTML5. An example of what I am looking for is similar to this website When you scroll on the page, there are links such as All, Intro, Solution. Clicking on any link sh ...

What could be causing the first bar in Chart.js to appear smaller or not show up at all?

Hey there, I'm currently working on displaying some bar charts using Charts js. However, I've run into an issue with the first column not showing up correctly. Here is my code snippet: var options = { scales: { yAxes: [{ display: tru ...

Error: The JS Exception has not been handled, as it is stating that 'undefined' is not an object when evaluating 'global.performance.now' in react-native-tvOS

I am currently working on a React-Native-tvOs app and despite following all the instructions from the react-native-tvOs GitHub page, I keep encountering an error when running the default template app. Even after running the script provided on the GitHub re ...

Interacting with dotnet core 3.1 Razor Pagemodel using Ajax in Bootstrap-table

$("#mTable").bootstrapTable({ method: "POST", url: "@Url.Page("Listing", "Query")", pagination: true, sidePagination: "server", ajaxOptions: { headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]' ...

What could be the reason for the <ul> and <li> tags showing up on my website's DOM?

I'm attempting to showcase cards on my webpage, but the text I'm displaying contains some code snippets like the one illustrated below: <div class="app"> <h1> All Fishes and Their Photos</h1> <ul v-for="(fi ...

What is the best way to retrieve a JSON object from within a nested JSON object within another parent object?

I am facing an issue with accessing a nested json object in JavaScript. The main json object contains another json object called "from", which in turn has a json object named value, and inside value is the address property that I need to access. Here' ...

Is it feasible to have my progress bars load only upon clicking the link for my div?

I have a link to my div called mySkills, and currently the progress bars load automatically when I access my page. However, I only want the progress bars to load when I click on the link (href) to this specific div mySkills. How can I achieve that functi ...

I'm looking for a PHP or Node.js OAuth library specifically for the Bitbucket API. I need to be able to make AJAX calls and interact with the library seamlessly

I am looking for a PHP-based library similar to loginWithBitbucket.php. This library should allow me to send authorization requests, which will trigger the opening of a new tab prompting the BitBucket user to enter their login credentials for authorizati ...

Stop jQuery from adding duplicate values to a table

When I make an AJAX call using jQuery and PHP to receive JSON response, I am encountering a problem with duplicate values. The code is functioning correctly, but when selecting an option from the drop-down list, duplicate entries appear. The scenario invol ...

Retrieving data from a multidimensional array in an AJAX response using jQuery

When I use ajax to send data, the response I receive is a multidimensional array. $.ajax({ type: "POST", url: "/slideshow/list.php", data: imageId, success: function(data){ imagesList ...

Localizing Dates in JavaScript

I'm currently dealing with localization and globalization in an ASP.NET application. As I navigate through this process, I am encountering difficulties in getting the Date() function in JavaScript to function correctly based on the user's locatio ...

FormArray does not properly handle invalid input focus

Although everything functions correctly with a regular FormGroup, the issue arises when dealing with a FormArray as it fails to focus on the invalid input. Here is how my form is initialized: initForm() { this.parentForm= this.fb.group({ childFo ...

Restrict the hide/show functionality on a div to only operate within its specific radio group, without impacting the other radio groups within the form

I created a form with 3 radio groups that show different sets of divs based on the selection made. The issue I'm facing is that the current code hides radio content divs across all 3 radio groups. How can I fix this? My goal is to display all "Yes" c ...

Transform a REACT js Component into an HTML document

I'm working with a static React component that displays information from a database. My goal is to implement a function that enables users to download the React component as an HTML file when they click on a button. In essence, I want to give users ...

Angular encountered a SyntaxError due to an unexpected curly brace } character

After spending a lengthy hour trying to troubleshoot this issue, I am at a loss as to why it is not functioning correctly. I have been attempting to showcase a row of images on a webpage using Angular based on data fetched from a json file. Unfortunately, ...

Place the retrieved data from the API directly into the editor

I've integrated the LineControl Editor into my app and everything is functioning perfectly, except for when I attempt to insert text into the editor. Here's the link to the LineControl GitHub page: https://github.com/suyati/line-control/wiki Fo ...

Error: JSON-JQUERY cannot retrieve the length of a null property

A problem has arisen with its function and is displaying in the console: Uncaught TypeError: Cannot read property 'length' of null. I am unable to understand why this is happening. function shownameplaylist(){ $.getJSON( "js/json/nameplaylist.js ...

Storing an item in the list using localStorage

Creating a dynamic list that utilizes the localstorage feature to save JSON array data has presented me with a challenge. The error displayed in Firebug is as follows: SyntaxError: JSON.parse: unexpected keyword var cli=JSON.parse(table[i]); Below is ...