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

Error in jQuery: the variable has not been defined

I am currently working on creating a custom plugin using the code below. I have encountered an error at the line if(options.controls == true) The specific error message says 'options is not defined'. How can I properly define this variable? ( ...

Gutenberg NPM remains in its original state without any alterations

I experienced some issues with the NPM when making changes in blocks or other elements as the changes were not working properly. Below is my gutenberg.php file: function MyBlocks() { wp_register_script('blocks-js', get_template_directory_ ...

Displaying a spinner within Bootstrap tabs to indicate content is loading via ajax

Using Bootstrap 3 tabs and AJAX to load tab content can sometimes result in slower loading times. To address this issue, it would be beneficial to incorporate a spinner within the tab content to indicate that the server is processing the request. Is there ...

Troubleshooting multiple element visibility problems with jQuery

Please take a look at the code snippet below. $(document).ready(function(){ $(".like-btn").hover(function() { var rowid = $(this).attr("data-rowid"); $(".reaction-box[data-rowid='" + rowid + "']").fadeIn(100, function() { $(".reaction ...

Exploring elementary Expressjs query concepts

Just getting started with nodejs and feeling a bit confused. I have a form on my website where users can submit information, and I want to display a response message in an HTML element once the form is submitted. I've been using body parser and Jade v ...

Error in Typescript occurrence when combining multiple optional types

This code snippet illustrates a common error: interface Block { id: string; } interface TitleBlock extends Block { data: { text: "hi", icon: "hi-icon" } } interface SubtitleBlock extends Block { data: { text: &qu ...

Having trouble converting Buffered Byte Array into Image in Browser

Hello there! I am currently facing an issue while attempting to generate an image from a buffered byte array. The reason behind this is that I need to transfer the image from the server to the client using JSON. Below is the code snippet in question: The ...

Is it necessary to utilize body-parser in our code?

In my research, I've noticed that many tutorials recommend using both express.json and bodyParser.json middleware. But aren't they essentially performing the same function? ...

Receiving the most recent data in a protractor examination as a text string

My goal is to fetch an input value for a specific operation in protractor. I am attempting to make an ajax request using protractor and need to assign a unique value (referred to as groupCode) to a JSON object that will be sent to the server. Initially, I ...

Having trouble utilizing props with Vue axios? Running into an undefined error? Unsure how to properly use props with axios?

https://i.stack.imgur.com/QfCDG.png There seems to be an issue with my saveComment() function in CommentList.vue. It can't find the comments' post_id and causes this error: CommentList.vue?6c27:107 Uncaught TypeError: Cannot read properties of u ...

Each container has its own div counter

Help needed to complete this code. The task is to count the number of .resp-containers in each container separately. Then, based on that count, assign a corresponding class to each element within the containers. Check out the code here $(document).ready(f ...

Ajax is able to fetch the URL without any issues, but the page is not being updated as expected. Instead,

I am currently working on implementing next/prev buttons using JavaScript, and have utilized a DynamicPage script for testing purposes. The only modification I made was to the beginning of the URL variable in pagenumber.js, although it essentially delivers ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

Struggling to display Firebase Auth information resulting in 'undefined' value within React web application

When loading a user's profile page, I am trying to display their displayName and email information retrieved from Firebase Auth. I have implemented this logic within the 'componentDidMount' method by updating the state with the response dat ...

What is the best way to search for multiple terms within a string using JavaScript?

Within my programming code, I have a string labeled S, and a collection of strings named allItems. The strings within allItems may share common "sub-words", but no element is ever an extension of another: // Example of good use where both strings contain & ...

Press the button using the spacebar

I am facing an issue where I have a button with an anchor element that I need to trigger with the spacebar key for accessibility purposes. However, instead of triggering the button, pressing the spacebar causes the page to jump down when the button is in f ...

Implementing event listeners with Angular UI-Router

Currently, I am working with Angular 1.4.5 and Angular Ui Router. I am facing an issue where I am trying to utilize addEventListener to execute a function when a text field is blurred. The challenge I am encountering is that during the load state, the elem ...

405 error: NGINX blocking POST method in Django DRF Vue.js application

I have encountered a strange issue while building my ecommerce site. Everything seems to be working fine, except for the forms. When attempting to post content, I keep receiving a 405 method get not allowed error. It's confusing as I am trying to use ...

Enhance fullness to facial features

Creating walls by forming faces using specific points is a successful process for me. However, I am now looking to add thickness to these walls, and I am unsure of the best approach. Below is the code I currently use to create the walls: makeWall(start, ...

Ways to resolve the problem of connecting Provider with my store and efficiently transmitting data to components in my Redux-React application

Encountering an error that reads: Uncaught Error: Could not find "store" in either the context or props of "Connect(WebShop)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(WebShop)". Despite havin ...