The MVC Controller is unable to retrieve decimal values from an Ajax POST request

I am facing an issue with the POST function in my code. While string and integer values are reaching the Controller without any problem, double values are not being received on the server side. Interestingly, when I test on my local machine, everything works fine. Can anyone explain why this behavior is occurring?

Below are snippets of my JS and Controller codes:

var cmbvdf = $('#cmbvolDec').data('kendoComboBox');
var cmbvdfval = cmbvdf.value();
var cmbadf = $('#cmbamtDec').data('kendoComboBox');
var cmbadfval = cmbadf.value();
var cmbCur = $('#cmbCurrency').data('kendoComboBox');
var cmbcurrency = cmbCur.value();
var cmtheme = $('#cbmTheme').data('kendoComboBox');
var cmbvaltheme = cmtheme.value();
var cmblang = $('#cmbLanguage').data('kendoComboBox');
var cmbvallang = cmblang.value();
var custname = $("#txtCustName").val();
var websitetitle = $("#txtWebName").val();
var zoom = $("#txtZoom").val();


var lat1 = $("#txtLat1").val();
var lon1 = $("#txtLon1").val();
        var url = '../Setting/SaveRecords';
        $.ajax({
            type: "POST",
            url: url,
            data:JSON.stringify({ 'volumeDecimalFactor': cmbvdfval, 'amountDecimalFactor': cmbadfval, 'currency': cmbcurrency, 'theme': cmbvaltheme, 'language': cmbvallang, 'customerName': custname, 'lat1': lat1, 'lon1': lon1, 'web': websitetitle, 'zoom': zoom }),
            contentType: 'application/json, charset=utf-8',
            traditional: true,
            success: function (data) {
                //do something
            }
        });

This is how my C# Controller looks like:

    public ActionResult SaveRecords(string volumeDecimalFactor, string amountDecimalFactor, string currency, string theme, string language, string customerName, double? lat1, double? lon1, string web, double? zoom)
    {
         //When testing locally, I can retrieve double values without any issues.
         //However, after publishing to the server, the values come back as null!
    }

NOTE:

In the Google Chrome Network Tab, here is the Request Payload:

amountDecimalFactor: "2"
currency: "4"
customerName: "Fuel Card System"
language: "1"
lat1: "41.071789"
lon1: "28.980325"
theme: "4"
volumeDecimalFactor: "2"
web: "WebProject"
zoom: "5.2"

It's worth mentioning that my local PC and the Server are located in different countries.

Answer №1

To prevent such situations, it is recommended to construct your JSON as a single string and transmit it to the Controller. You can achieve this by following these steps:

<script type="text/javascript">
var cmbvdf = $('#cmbvolDec').data('kendoComboBox');
var cmbvdfval = cmbvdf.value();
var cmbadf = $('#cmbamtDec').data('kendoComboBox');
var cmbadfval = cmbadf.value();
var cmbCur = $('#cmbCurrency').data('kendoComboBox');
var cmbcurrency = cmbCur.value();
var cmtheme = $('#cbmTheme').data('kendoComboBox');
var cmbvaltheme = cmtheme.value();
var cmblang = $('#cmbLanguage').data('kendoComboBox');
var cmbvallang = cmblang.value();
var custname = $("#txtCustName").val();
var websitetitle = $("#txtWebName").val();
var zoom = $("#txtZoom").val();


var lat1 = $("#txtLat1").val();
var lon1 = $("#txtLon1").val();

  var json = {
              cmbvdfval : cmbvdfval,
              cmbadfval : cmbadfval,
              cmbcurrency : cmbcurrency ,
              cmbvaltheme : cmbvaltheme ,
              cmbvallang : cmbvallang ,
              custname : custname ,
              websitetitle : websitetitle  ,
              zoom : zoom ,
              lat1 : lat1 ,
              lon1 : lon1 
             };

    $.ajax({
        url: '@Url.Action("SaveRecords", "Setting")',
        type: 'post',
        dataType: "json",
        data: { "json": JSON.stringify(json)},
        success: function (result) {
             //perform desired actions upon success
        },
        error: function (error) {
            console.log(error)
        }
      });

</script>

You can retrieve the values in your Controller using the following approach:

using System.Web.Script.Serialization;

[HttpPost]
public ActionResult SaveRecords(string json)
{

        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));

        //Access the variables from AJAX call here
        var zoom = jsondata["zoom"];
        var lat1 = jsondata["lat1"];

        //Perform operations with the retrieved variables    

    return Json("Success");
}

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

Securing a namespace using passport js: A step-by-step guide

Imagine I have set up a specific route with the following namespace: app.use('/registered', userRoute); Recently, I wrote the following passportjs function: app.get('/logged/dashboard', function (req, res) { if (req.user === undefi ...

Is it possible to use [DataRow] in Selenium tests within MSTest at the TestClass level?

Thank you in advance! In the process of creating a Selenium framework using C# and MSTest, I have encountered a roadblock while attempting to implement data-driven tests. What I am aiming for: I need to support logging into the application under test with ...

ways to assign the total of string array elements to the $scope variable

I've been working on binding the total sum of selected checkboxes within a table. I'm almost there, but something isn't quite right. The image above shows 2 checkboxes selected. The code snippet below showcases my current implementation. An ...

What is the process for displaying content in a 403 response in a Rails application?

I am currently facing an issue where my controller action returns a 403 with JSON data when it fails, such as ActiveRecord errors. However, in Chrome's developer tools, the response content appears to be empty. Is it more appropriate for me to return ...

Compilation unsuccessful. The LineGraph.js module could not be located due to recursion in resolving

After successfully installing react-chartjs-2 and chart.js using the command npm install --save react-chartjs-2 chart.js, I encountered an error when attempting to use LinkGraph: Failed to compile. ./src/LineGraph.js Module not found: Recursion in resolvi ...

Command for Sniping with Discord.js

I am currently working on creating a snipe command using Discord.js in my bot. I have set up command handlers and everything seems to be working fine, including the on messageDelete event. However, I encounter an error when I delete a user message and try ...

Utilizing AngularJS to create bound checkboxes

I am struggling with two checkboxes, one with Data Binding and the other without Data Binding. The code snippet below illustrates this: <html ng-app="notesApp"> <head><title>Notes App</title></head> <body ng-contro ...

Encountering a node globby error when implementing multiple patterns

Currently, I am successfully using node glob for folder1 as shown below: glob('folder1/*.js'), function(err, files){ if (err) { console.log('Not able to get files from folder: ', err); } else { files.forEach(function (file) ...

How can user input be converted into a JavaScript variable?

Looking for help with my webpage - I want users to input their name and age. After hitting submit, I'd like the first input to be stored in a variable called 'name', and the second input in a variable called 'age'. Is this doable? ...

Tips for successfully transferring values from an onclick event in JavaScript to a jQuery function

I am encountering a challenge with an image that has an onclick function associated with it. <img id='1213' src='img/heart.png' onclick='heart(this.id)'> This particular function needs to be triggered : function heart ...

Ways to convert a JavaScript object into restful GET parameters in order to append them to the end of an API URL

Suppose we have a JSON object like this: { name: 'Tony', age: '20', birthday: '20180101', } What is the best way to convert it into parameters that can be appended at the end of a RESTful GET API URL, such as the ...

Filtering Array Elements in Vue JS: A Step-by-Step Guide

In my Vue Js 2.0 application, I am working on filtering elements in an array format. Here is the code snippet: const search = this.search_by_name.toLowerCase() const searchContact = this.search_by_contact.toLowerCase() return this.meetings .map(i => ...

Enhancing Vuejs Security: Best Practices and Tips for Secure Development

Recently, I developed a Web Application utilizing Vue.js and fetching data from the backend using 'vue-resource' in combination with Express and Postgres. Now, my main objective is to enhance its security by integrating an API Key. I am somewha ...

What is the best way to add borders to the cities on interactive SVG maps?

I'm currently developing Interactive SVG Maps showcasing Turkey. The map consists of 81 cities, each represented by <g> elements, and their respective districts, created as child elements within the city elements. It's worth noting that the ...

Having trouble with updating React state? The useEffect hook runs when attempting to change the state, but it seems to have the

Having worked with useEffect and its ability to trigger after a state variable has been updated, I am well-versed in its functionality. I'm currently drafting this post on my phone while away from home. Here's the setup I have: const [dateValue ...

Error: The function $(...).draggable is not recognized" and "Error: The object $.browser is not defined

I encountered an error stating, TypeError: $(...).draggable is not a function. To resolve this issue, I added jQuery as follows: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> < ...

Adjust the range directly in ng-repeat from the directive

I am working with HTML code that looks like this: <div dir-paginate="x in comments | itemsPerPage: commentsPerPage"> HERE IS DIRECTIVE FROM BLEOW </div> My goal is to update the commentsPerPage scope within the directive... Below is a direct ...

Is it possible to swap out images using srcset attribute?

Currently, I am facing an issue regarding changing the img on mobile and tablet devices to display different images. As a beginner with jQuery, I couldn't resolve it using that framework, so I am exploring options with html5. I am wondering if there ...

Shader material for border and overlay effects in THREE.js

Can a sphere in THREE.js be given a material shader to achieve a unique visual effect like the one shown here? (I'm specifically interested in replicating the border, glow, and streak on the red sphere.) https://i.sstatic.net/rjfkm.png If this is po ...

Challenges encountered while creating a Number Tables Program (such as displaying 12 x 1 = 12) using Javascript

Currently, I am working on developing a program that can generate mathematical tables for any given number. For example: 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 To achieve this, the user should provide the following inputs: (1) The number they want ...