Controller experiencing issues with Ajax passing null value

My webpage features a dropdown menu with a list of ID's to choose from. When a customer selects an option, it should update the price total displayed on the page. To achieve this functionality, I'm working on implementing an AJAX call that will update the total whenever a different ID is chosen from the dropdown.

$("#BrandId").on('focus', function () {
    // Store the current value when focused and upon change
    previous = this.value;
}).change(function () {
    alert("Previous: " +previous);
    sel = this.value;
    alert("Selected: " +sel);
    $.ajax({
        cache: false,
        type: "get",
        contentType: "application/json; charset=utf-8",
        url: '@Url.Action("GetBrandCost", "Shocks")',
        data: JSON.stringify({ idp: previous, id: sel }),
        dataType: "json",
        aysnc: false,
        success: function (data1) {
            alert(data1);
                //ShockTotal = $("#ShockTotal").html();
                //ShockTotal = ShockTotal / 1;
                ////ShockTotal = ShockTotal - data1;
                //$("#ShockTotal").html(data1);

        }
    });
});

Although the alerts work as expected, I'm encountering an issue where the AJAX call doesn't pass the IDs to the controller properly, resulting in the controller receiving null values.

 public decimal GetBrandCost(string idp, string id)
    {
        decimal costp = 0;
        decimal cost = 0;
        if (id == "" || id == null || idp == "" || idp == null)
        {
            return 0;
        }
        ShockBrand brandp = db.ShockBrands.Find(idp);
        costp = brandp.Cost;
        ShockBrand brand = db.ShockBrands.Find(id);
        cost = brand.Cost;
        cost = cost - costp;
        return cost;
    }

As the values are null, the code flow hits the if statement, with the method returning zero within the success block. Despite trying to specify content types, it hasn't resolved the issue for me. I believe there might be a simple fix that I am missing.

Answer №1

When using the browser console, this

$.ajax({
        cache: false,
        type: "get",
        contentType: "application/json; charset=utf-8",
        url: 'http://google.com',
        data: JSON.stringify({ idp: 1, id: 2 }),
        dataType: "json",
        aysnc: false,
        success: function (data1) {
           console.log(data1)

        }
    });

sends a request to

http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799
, which is incorrect

However, when sent without stringify

$.ajax({
        cache: false,
        type: "get",
        contentType: "application/json; charset=utf-8",
        url: 'http://google.com',
        data: { idp: 1, id: 2 },
        dataType: "json",
        aysnc: false,
        success: function (data1) {
           console.log(data1)

        }
    });

it returns

http://google.com/?idp=1&id=2&_=1440696381239
(check Network tab)

Therefore, avoid using JSON.stringify

The reason it works is that your asp.net controller action accepts simple typed parameters and jQuery is smart enough to determine how to send the data. For GET requests, it will send string representation of objects. So, when configuring the URL, ASP.NET understands the conventions and matches the request to the appropriate action

Don't just take my word for it, verify it yourself

Use Chrome Dev Console for more insights

Answer №2

After making some adjustments, I managed to resolve the issue of receiving a null value in the controller action. The key was removing the following lines from my code:

 $(function () {
    $.noConflict();
    $.ajax({
        type: "POST",
        url: "../Case/AjaxMethodForUpdate",
        data: {typ: $('#typeID').val()},
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        },
        error: function (response) {
            alert(response.d);
        }
    }); 

Answer №3

Simply input it as follows:

let requestData = { providerId: previous, userId: selected };
data: requestData

No requirement for specifying dataType and contentType.

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

Utilizing JQuery to extract the image title and render it as HTML code

I am currently facing an issue with displaying an image in my project. I want to hide the image using CSS (display: none) and instead, retrieve the value of its title attribute and display it within the parent div by utilizing JQuery. Despite knowing tha ...

Display additional inputs using the PHP Foreach Loop depending on the selection made

I have a PHP Foreach loop that includes a "Quantity" input field. When users select a quantity, the corresponding number of new inputs should be displayed. For example, if the user chooses a quantity of "3", then 3 new inputs should appear for that item. K ...

Updating the content within a div following the submission of a contact form 7

I'm struggling with my contact form. I want the content of my contact form div to change after clicking submit on the form. I've been searching for a solution, but so far, no luck. Here is what I have: Form (div1) with input fields, acceptance c ...

trouble encountered while sending data to php using ajax and json

Despite trying multiple solutions, my script is still not working properly. It functions without the $_POST value and without JSON, but when both are included, it fails to work. The error message displayed by the function is as follows: <b>Notice< ...

Decoding a series of structures within a list

Attempting to deserialize from JSON into a List<struct>, but continues to have the object returning null. The source JSON data types are correct and no errors are being thrown in the code, leaving confusion as to why it is not functioning. The class ...

Issue with getStaticProps not updating fetched values in Next.js production environment

I am currently working on building a blog using Next.js. Since the back-end is taken care of by another team, I am utilizing fetch API calls in getStaticProps to retrieve my articles, even though it may be considered best practice to interact with the data ...

Looking for some help with tweaking this script - it's so close to working perfectly! The images are supposed to show up while

Hey everyone, I'm struggling with a script issue! I currently have a gallery of images where the opacity is set to 0 in my CSS. I want these images to become visible when scrolling down (on view). In this script, I have specified that they should app ...

Using JavaScript to bring in npm packages

My understanding of javascript modules is still lacking. I recently embarked on a new project that required a library from npm. https://www.npmjs.com/package/random-color-pair After running npm i random-color-pair This created a "node modules" folder wh ...

A guide on customizing the appearance of individual items in a vue v-for loop based on specific conditions

I am currently developing a multiple choice quiz game and I want the selected answer by the user to change color, either red or green, depending on its correctness. To achieve this, I have created a variable called selected that correctly updates when the ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...

Interactive JQuery calendar

Can anybody assist me with this issue? I am seeing question marks in the graphic and I'm not sure why. I remember encountering these symbols before and I believe it has something to do with charset. Currently, I am using: <meta http-equiv="Content ...

How to upload multiple files using AngularJS and Laravel without using a form tag

I am seeking a solution to upload multiple files without using the form tag, utilizing AngularJS with Laravel 5.2. The code snippet below is functional for uploading a single file but fails when attempting to upload multiple files. Here is the HTML Code: ...

Displaying genuine HTML content in a React application using Algolia Instantsearch

After setting up a demo app using React with an Algolia search feature, I uploaded some indices into Algolia. The content consists of raw HTML. Is there a way to display this content as real HTML using Algolia? ...

What is the process for obtaining a client-side cookie using next.js?

I'm currently facing an issue where I can't seem to maintain a constant value for the isAuthenticated variable between server-side and client-side in next.js. In my setup, I am using a custom app.js file to wrap the app with Apollo Provider. The ...

Using Query strings in JavaScript: A Quick Guide

I recently completed a calculator project with only two pages. However, I am struggling to figure out how to pass input field values from one page to another. Despite trying multiple methods, nothing seems to be working. Does anyone know how to successful ...

Issues with Rock Paper Scissors Array in Discord.js V12 not functioning as expected

I'm currently working on implementing an RPS game in my Discord bot. I want to create a feature where if the choice made by the user doesn't match any of the options in the list, it will display an error message. Here is the code snippet that I h ...

Access and retrieve xlsx file from a Java-based Restful backend

When I upload an excel file from my UI using an ajax-post call and try to read it from my backend Restful service Java code, I am encountering issues in printing the excel file contents correctly. Although the file name and other attributes are printing co ...

Ways to implement a custom scrollbar across an entire webpage:

I am trying to implement the Jquery custom content scroller on my webpage to replace the default scrollbar. However, I am facing difficulties in getting it to work properly. You can view my code on Codepen. Although the plugin works fine with smaller blo ...

Execute the function when the form is submitted and show the total of the two values

I am currently working on a straightforward custom module for Drupal 7. This module takes two numeric values and upon submission, displays the sum of these values on the same page. While I have the form set up, it is not yet complete. I am facing some dif ...