The AJAX functionality is not triggering the necessary C# controller method

I have been facing a challenge with my AJAX implementation as I am still new to using it. The problem arises when trying to reach the C# method it should call - even after setting a breakpoint, the code is never reached and no errors are displayed.

While debugging with FireBug, I confirmed that the getCheckBoxes function is being called and executed.

The C# method I am trying to execute with AJAX is located in TestScriptResultsController. Despite removing the internal code, the method remains unreachable. I have attempted both POST and GET methods without success. Any assistance would be greatly appreciated.

getCheckBoxes = function getCheckBoxes () {
    //var firstDate = '@Model.FirstDate';
    //var lastDate = '@Model.LastDate';
    var fDateChanged = $("#FirstDate").datepicker('getDate');
    var lDateChanged = $("#LastDate").datepicker('getDate');
    var platformConfig = '@Model.PlatformConfigSelected';
    var triggered = '@Model.TriggeredSelected';

    $.ajax({
        url: '@Url.Action("BranchCheckBoxes", "TestScriptResults")',
        type: 'POST',
        data: { fDateChanged: firstDate, lDateChanged: lastDate, platformConfig: platformConfig, triggered: triggered },
        success: function (data) { $('#checkBoxes').html(data); }
    });
}

The controller action :

    public ActionResult BranchCheckBoxes(DateTime firstDate, DateTime lastDate, string platformConfig, string triggered)
    {

        return PartialView(trs);
    }

Answer №1

  1. Make sure to correct your JavaScript object initializer syntax for data. The correct format is:

    data: { firstDate: fDateChanged, lastDate: lDateChanged, platformConfig: platformConfig, triggered: triggered }
    Remember, the proper syntax is { 'key': 'value' }

  2. If you are not inside a Razor page,

    '@Url.Action("BranchCheckBoxes", "TestScriptResults")'
    will not work. Ensure that your JavaScript code is within a .cshtml or .vbhtml page, or consider using
    url: '/TestScriptResults/BranchCheckBoxes/'
    instead

  3. Do not forget to add an [HttpPost] attribute to BranchCheckBoxes(), as MVC defaults to GET for controller actions:

    [HttpPost]
    public ActionResult BranchCheckBoxes (...)
    

Answer №2

After Jason pointed me in the right direction regarding the HTTP response, I was able to find the solution to my issue. The problem stemmed from .datepick('getDate') returning an object instead of a string, causing issues before entering the ActionResult method I had set up. I made adjustments to how I retrieved the value from the datepicker, updated my data line in the AJAX call, and revised my actionResult parameters. Everything is now functioning properly. Is there a way for me to give credit to Jason on StackOverflow for his invaluable assistance?

Here is some relevant code:

            $(function () {
            $("#FirstDate").datepicker()
              .on("input change", function (e) {
                  var firstDateChanged = $(this).val();
                  firstDateChange();

              });

        });

Adjusted AJAX data:

data: { firstDate: firstDateChanged, lastDate: lastDateChanged, platformConfig: platformConfig, triggered: triggered },

Controller modifications:

        public ActionResult BranchCheckBoxes(string firstDate, string lastDate, string platformConfig, string triggered)
    { }

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

fetching indexeddb information using the equivalent of a "WHERE IN (a,b)" query

I've been working on transitioning from websql to indexeddb, but I'm struggling to recreate the SELECT query: "SELECT * FROM tableA WHERE cid ='"+cid+"' AND hid IN("+hid+",1) ORDER BY hid DESC LIMIT 1"; function getMyData(e) { var ...

The query attribute of the http_incomingmessage in Node.js is not empty, causing Express to have trouble parsing the query parameter

While utilizing node version 6.9.4 and express version 4, there seems to be an issue with the creation of the IncomingMessage object in _http_common.js. Specifically, on line number 60, the parser.incoming.query function is being set to a value (usually it ...

Is there a way to personalize the settings of this JavaScript function?

I've created a javascript function to block special characters... function customTextValidation(text) { !(/^[A-zÑñ0-9]*$/i).test(text.value) ? text.value = text.value.replace(/[^A-zÑñ0-9]/ig, '') : null; } The issue I'm facin ...

The image slider on the front end is malfunctioning

Starting out as a novice on a new website project, I typically work with Dreamweaver and also do some hardcoding in HTML and CSS. This is why I decided to try my hand at Magento. While making a change in the CMS / Static Block section, I accidentally brok ...

Would combining node.js with express for the back-end and emberjs for the client side be a suitable choice for my project?

As a seasoned web developer, I have limited experience with nodejs and have yet to dive into the world of emberjs (although I have worked extensively with backbone). I am embarking on a new project to create a web-based writing application focused on lite ...

Issue with loading Three.js asynchronously

My attempt to determine the maximum value of a point cloud data using the following code proved unsuccessful. import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader"; let max_x = -Infinity; function initModel() { new PLYLoader().load ...

Unable to showcase information in the center of an HTML document

Hello, I'm facing an issue with my HTML page that has a left vertical nav-bar. Despite my efforts, I can't seem to display content (text) in the center of the page as shown in the screenshot with the red oval. I've attempted inserting text ...

What is the reason objects cannot be compared in JavaScript?

I have a straightforward code snippet here. Its purpose is to authenticate the user against the author of the post and grant the authenticated user access to edit the post. exports.edit = function(req, res){ Post.findById(req.params.post_id, function ...

Logo remains in place when scrolling halfway down the page

I have a logo that I want to stay halfway up the home page when scrolling, as if fixed in place until it reaches the footer. body { background-color: #fff; margin: 0; } nav { position: sticky; top: 0; width: 300px; height: 80px; margin:4 ...

"Optimizing website performance with Ajax and securing data with

As I work on developing an Ajax chat application, I have found the need to periodically call a PHP script that checks for new messages in the database. I recently learned about PDO prepared statements and thought they could be useful since only one variab ...

What is the most stylish method for merging a removeCartItem function with an addCartItem function?

Is there a way to combine these functions into a more concise and elegant piece of code? While the current setup works fine, it feels redundant to have two large functions that essentially do the same thing. const modifyCartItem = (cartItems, productToMo ...

Discover the way to locate controls within a repeater in Web Forms

Having trouble locating a Literal within a Repeater nested in another UserControl. Below is the structure of the UserControl: <nav role="navigation"> <ul> <li><a href="/"<asp:Literal id="litNavHomeActive" runat="server" />& ...

Is it possible to trigger a single event listener by either of two events?

I need a search functionality that triggers a method on a bean either through a click event or a blur event, whichever occurs first. This is necessary because I want the search results to display as the user types, but also to work if the user copies and p ...

Tips on Avoiding Initial Click Activation

I've been working on a JavaScript function that dynamically generates an iframe with a button that, when clicked, deletes the iframe itself. Here are the functions I've written: function createIframe (iframeName, width, height) { var ifram ...

Trying to access a jQuery variable outside of the success function results in a null value

I have been researching this issue in various forums, but I haven't been able to successfully apply the code provided by other tech experts. My problem lies in accessing a variable inside a jQuery success function, which currently throws null due to b ...

Getting HTML from Next.js middleware - a step-by-step guide

Is there a way to send the HTTP Status Code 410 (gone) together with a customized HTML message? I want to display the following content: <h1>Error 410</h1> <h2>Permanently deleted or Gone</h2> <p>This page is not foun ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

ASP.NET AJAX call fails to update the table due to null response

I am currently attempting to update my table by making an Ajax call using the following code snippet: var client = {}; client.ClientId = row.find(".ClientId").find("span").html(); client.Name = row.find(".Name").find("span").html(); ...

What is the reason for the blank first page when printing with vue-html2pdf, a tool that utilizes html2pdf.js internally?

Hey there, I'm currently experiencing issues with printing using a Vue component named vue-html2pdf. Here are the problems I'm facing: The pagination doesn't break the page when content is added, resulting in a 3-page printout. The first p ...

Ensuring the Safety and Protection of Webmethods

Incorporating JQuery AJAX with webmethods can present a challenge in terms of security. Given that regular session authentication does not function within webmethods, it raises the question: what strategies exist to safeguard webmethods from potential ex ...