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

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Issue: The hydration process has failed due to a discrepancy between the initial UI and the server-rendered content when utilizing the Link element

Exploring Next.js, I stumbled upon the <Link/> component for page navigation. However, as I utilize the react-bootstrap library for my navbar, it offers a similar functionality with Nav.Link. Should I stick to using just Link or switch to Nav.Link? ...

Tips for resolving the problem of Google Maps repeatedly appearing when utilizing the Auto-Loading feature

I need help understanding the issue that arose when loading the Google Maps API. "You have included the Google Maps API multiple times on this page. This may cause unexpected errors." This error occurred while attempting to automatically load the API. B ...

What is the method of displaying a querystring on my Angular view page without relying on a controller?

My experience lies in utilizing AngularJS 1. This excerpt showcases the stateprovider configuration present in my config.js file: JavaScript .state('projects', { abstract: true, url: "/projects", templateUrl: "views/common/master_pa ...

Challenges with JArrays

Having issues with JSON Parse and Jarray.Length. The goal of this app is to: metin variable serves as the search string. For example, if I input "DDDDDD", the SOFTWARE will search in the JSON file for "DDDDD" and display DDDDD's features on the consol ...

Tips for incorporating `new google.maps.Marker()` with `vue2-google-maps` are as follows:1. First

Due to certain reasons, I find myself having to utilize new google.maps.Marker() with vue2-google-maps, but I'm unsure of where to begin as most documentation and tutorials use <GmapMarker ... /> in the HTML section instead. I've attempted ...

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 ...

Troubleshooting issue with C# Ajax success response not triggering alert

I am facing an issue where the alert box for success does not show even though the code successfully inserts contact details using ajax and C#. Strangely, when I debug through the JavaScript debugger in Chrome, the alert pops up as expected. Here is the co ...

Steps for loading a different local JavaScript file by clicking on a button

My goal is to reload the browser page and display a different ReactJS component/file when a button is pressed. Initially, I attempted using href="./code.js" or window.location="./code.js" within the button props, but unfortunately, it did not yield the des ...

Capybara's attach_file function is not properly activating the React onChange handler in Firefox

Currently, I am conducting tests on the file upload feature of a React-built page. The page includes a hidden file input field with an onChange event listener attached to it. Upon selecting a file, the onChange event is triggered and the file is processed ...

What is the best way to convert a List of objects to JSON using a dynamic variable?

I have a need to serialize a list of objects in a specific way: Imagine I have the following C# class: public class Test { public string Key; public string Value; } List<Test> tests; When I serialize this list (return Json(tests.ToArray()) ...

Embarking on the journey of transitioning code from server-side to client-side

Currently, I am looking to transition the code behind section of my asp.net web forms application to client-side ajax or javascript - still deciding on which route to take. The main goal for this change is to ensure that the application remains functional ...

Attempting to eliminate an HTML element using JavaScript

Currently, I am working on creating an image rotator in JavaScript. The CSS fade animation I have applied only seems to work during element creation, so I am forced to remove the element on each loop iteration. The main issue I am encountering is related ...

Obtain information from express middleware

I am currently working on a project using node.js. As part of my application, I have developed a middleware function that is triggered whenever a GET request is made. This occurs when someone visits the home page, profile page, or any other page within my ...

What are the steps to start up a NodeJS API using an Angular app.js file?

Currently, I am following various online tutorials to develop a web application using the MEAN stack and utilizing a RESTful API. I have encountered some challenges in integrating both the API server and Angular routes. In my project, I have a server.js f ...

Issue with continuous loader malfunction

I integrated a 3-second mini-loading animation on my website. It shows up every time I refresh the site or navigate to another page. The issue I'm facing is that once I add the loading section, it never stops (it should only last for 3 seconds). Usua ...

Change the font awesome class when the button is clicked

Here is the code I have in this jsfiddle. I am trying to change the font awesome icon on button click using javascript, but it doesn't seem to be working. I am new to javascript, so please pardon me if this is a silly question. HTML <button id="f ...

AngularJS $http.get request failing to retrieve data

I've been delving into AngularJS lately, but I'm having trouble displaying the data from my MySQL database on the view. Here's the code snippets I'm working with: todoController.js angular .module('todoApp') .control ...

Looking to retrieve a cookie within Vue Router in Vue 3? Utilize the following approach within your router's `index.js

Scenario: Developing a Vue3 app with express as the API backend. Express utilizes express-sessions to create a server-side session that is transmitted to the browser and received in subsequent requests. I am in the process of implementing a route guard to ...

Using checkboxes in Struts2 with AJAX

I am struggling to properly position my AJAX called checkbox using a div with the ID <div id="reverse" style="position:absolute; left:500px; top:379px;"></div>. How can I align them in one row with three columns? When I use this code, the check ...