Executing [HTTPPost] request using JavaScript with ASP.NET

I have a controller method that fetches data from an API which I need to be able to call from two different places. The first location is the view (which is currently working), and the second is a JavaScript function.

Here is the beginning of the controller method:

[ActionName("ImportRosters")]
    [HttpPost]
    public ActionResult PerformImportRosterData(int id, int? actualLength, int? rosterLength)
    {
        var authenticator = Authenticator(id);
        var rosters = authenticator.Api().RosterData().ToDictionary(x => x.Id);

        var databaseRosterDatas = SiteDatabase.DeputyRosterData.Where(x => x.SiteID == id).ToDictionary(x => x.Id);

Javascript Function:

$("#btnDeputyRunNowUpdate").click(function() {
    $("#btnRunDeputyNow").modal("hide");
    ActualLength = $("#actualRunLength").val();
    RosterLength = $("#rosterRunLength").val();
    $.ajax({
        type: "POST",
        url: "/deputy/PerformImportRosterData",
        data: { SiteIDRoster, ActualLength, RosterLength }
    });
    SiteIDRoster = null;
    location.reload();
    $("#btnRunDeputyNow").modal("hide");
    toast.show("Import Successful", 3000);
});

Although all values are being properly set, I am encountering a 404 error on the URL line: POST 404 ()

I am looking for a solution that allows me to call this C# method from both HTML and JS.

Answer №1

Modifying the URL in your AJAX can be achieved by using:

url: '<%= Url.Action("YourActionName", "YourControllerName") %>'

or

url: @Url.Action("YourActionName", "YourControllerName") 

If you do not handle the result of the call, remember to include a success function like this:

 success: function(data) {//do something with the return}

Additionally, consider adding an error handler for better control over your AJAX call. Here is a full example on how it should look like:

$.ajax({
  url: "target.aspx",
  type: "GET",
  dataType: "html",
  success: function (data, status, jqXHR) {
   $("#container").html(data);
    alert("Local success callback.");
   },
   error: function (jqXHR, status, err) {
     alert("Local error callback.");
  },
  complete: function (jqXHR, status) {
     alert("Local completion callback.");
  }
})

For more information on AJAX, refer to this document

Update after Comment: A sample code snippet is provided below:

$("#btnDeputyRunNowUpdate").click(function() {
    $("#btnRunDeputyNow").modal("hide");
    ActualLength = $("#actualRunLength").val();
    RosterLength = $("#rosterRunLength").val();
    $.ajax({
        type: "POST",
        url: '<%= Url.Action("PerformImportRosterData", "DeputyController") %>',
        data: { SiteIDRoster, ActualLength, RosterLength },

        success: function(data) {
            console.log(data);
            console.log("TESTHERE");

        }
    });
}

UPDATE: Mismatch between controller parameters and AJAX call parameters was identified. Modify your AJAX call as shown below:

    url: "/deputy/PerformImportRosterData",
    data: { id: yourIDValue,  actualLength: youractualLengthValue,  
            rosterLength :yourrosterLengthValue }

Ensure all variable values are set in JavaScript, if they have no values, set them to null.

Copy paste the following code snippet and check for any errors:

$.ajax({
    type: "POST",
    url: "/deputy/PerformImportRosterData",
    data: { SiteIDRoster:999, ActualLength:1, RosterLength:2 }
});

If any errors occur, please let me know.

Answer №2

Having struggled for several days to find a solution, I finally devised a workaround by developing two separate methods for importing the data: one for the httpPost and another for import calling from javascript.

While not ideal, this approach gets the job done. Special thanks to Yuri for your assistance!

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

Getting the value of an object using jQuery

I am working on reading this XML file and extracting values from different nodes. While I can currently retrieve the value of a specific node, the issue arises when there are multiple nodes with the same name. As a result, when I try to get the value, I en ...

By default, the HTML table will highlight the specific column based on the current month using either AngularJS or JavaScript upon loading

I am working with a table of 10 products and their monthly sales data. Using Angular JS, I am looking to highlight the entire column based on the current month and year. Additionally, we will also be incorporating future expected sales data into the table. ...

"Enhance Your Design with Hovering CSS Backgrounds

Seeking assistance with changing the background image on span hover. If anyone can assist, I have included the complete code for the website below. Take a look at the full website code here: Pastebin CSS Pastebin JavaScript ...

Implementing pagination in a Node.js application using MongoDB.ORCreating

function implementPaginationForDigitalMigrationJoin(req, res, next) { DigitalMigrationForm.aggregate([ // Join with user_info table { $lookup: { from: DigitalMigrationFormList.collection.name, // other ...

Tips for incrementing the counter value with a button click in JavaScript

As a beginner in JavaScript, I am facing an issue with implementing an event where clicking the plus button changes the CSS style but does not increase the value. Similarly, clicking the menus button does not remove the last child element... I aim to disp ...

Instructions on extracting particular elements from a JSON document and converting them into an array

Here is a JSON array that I am working with: { "data": [ { "id": 6, "pnome": "dasda", "unome": "dad", "avatar": 1, "email": "d", ...

AngularJs throws an error: "Received an unexpected value when passing a number

Whenever I try to assign a value to $scope.formData.field_happy.und.0.value, I encounter the following error. An unexpected SyntaxError occurs: Unexpected number However, if I bind it to a model, everything works fine. I can't seem to figure out w ...

Is the maxJsonLength property in the web.config referenced by JQuery's Ajax?

Within my ASP.NET platform, I implement Jquery AJAX to retrieve JSON data (essentially a string) from a webservice upon clicking the search button: $.ajax({ type: "POST", url: url, data: JSON.stringify(parameterArray), contentType: "application/j ...

"Efficiently Input and Update Information in Details View Using Programming Language

I am attempting to programmatically insert or update data into a database from a detailsview without using a datasource directly. I have set this up in the Page_Load event. static string conn = ConfigurationManager.ConnectionStrings["AptechConnectionStrin ...

Step-by-step guide on opening a modal popup, retrieving information from a database, presenting it in the popup, and saving any modifications as per the user's instruction

In my current project, I am utilizing Flask along with psycopg2. One of the requirements is to create a page titled "List of Payments" which displays a table containing payment information. The manager has requested the ability to view card details and edi ...

Optimal strategies for managing exceptions in ASP.NET web applications

Currently, we are diving into the realm of exception handling within ASP.NET web applications using C#. Could you share some insights on the most effective practices for managing exceptions in this context? ...

I am having issues with my dropdown-list on my second script not functioning properly

Hello there! I'm new to this platform and English is not my strong suit, so bear with me. I've encountered an issue in my code that I need help with. Step 1: I successfully created the first dropdown list. Step 2: The second dropdown l ...

Using JavaScript to cheat on a typing test by automating the typing of letters

I am currently working on a solution to simulate key presses for a typing test. My idea is to extract individual letters from the text, store them in an array, and then simulate pressing each key with a delay between each press. Below is the HTML layout o ...

Tips on ensuring that the Angular frontend waits for the response from an Express REST call

Upon initializing my user Component, I want to trigger a REST-Call so that the user profile is displayed when the page loads. The process works smoothly as the component communicates with the service, which in turn contacts my express backend to make the n ...

Using HTML and Javascript files with AJAX can sometimes be problematic due to compatibility issues

Throughout the past seven years, I have dedicated my time to programming small websites for offline and private usage. Each project consists of an html file that links to a css file and a javascript file. The javascript file utilizes AJAX to load content f ...

Accessing a JSON value within the AngularJS controller for the purpose of making edits

Seeking assistance here, as I work with a JSON file to generate a timeline using AngularJS. While I've successfully utilized the ng-repeat loop in HTML binding to display dates, I now need to modify the date format – specifically, changing "2013-01- ...

Utilize jQuery AJAX function to fetch a PDF document from a PHP file

My PHP file, example_061.php, successfully creates a PDF that works fine when returned. Now, I am attempting to call this file using jQuery AJAX to display it on my screen. Here is my code: $("#proba").click(function() { // Perform ajax after checking ...

Tips for verifying the parameter value within ASP.NET MVC routes

In my ASP.NET MVC project with C#, I have a method defined as follows: public FileResult ViewImage(int ImageFileItemId, int MaxWidth, int MaxHeight, bool FixedWidthH ...

Failure when running npm start command in Nest js

After setting up a fresh Nest js on a new EC2 machine, I encountered an error when trying to run it for the first time. The error message indicated that the npm install process failed abruptly without any visible error: ubuntu@ip-172-31-15-190:~/projects/m ...

AngularJS: $digest must be run before calling $httpBackend.flush()

I'm struggling to understand why I have to use $rootScope.$digest() before my test can pass with $httpBackend.flush(). If I skip it, I end up with Error: No pending request to flush! This is the code for my test: it('should post a new task to ...