Retrieve data using ajax within an mvc framework

I am facing an issue where I am unable to receive the data sent with AJAX jQuery to a .NET server as a parameter, modify it in memory, and then convert it to JSON. Any assistance in resolving this problem would be greatly appreciated.

JAVASCRIPT

document.querySelector('input#btnGuardar').onclick = function (e) {
            e.preventDefault();
            var data = $('form#form_boleta').serializeJSON();
            $.ajax({
                type: "post",
                url: "/Comprobante/Factura",
                data: data,
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    if (result === "success") {
                        swal({
                            title: "¿Generar Otro Comprobante?",
                            text: "¡El comprobante se ha generado de manera correcta!",
                            type: "success",
                            showCancelButton: true,
                            confirmButtonClass: 'btn-success',
                            confirmButtonText: 'Si',
                            cancelButtonText: "No",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        },
                            function (isConfirm) {
                                if (isConfirm) {
                                    self.parent.location.reload();
                                } else {
                                    window.location.href = "/Plataforma/Dashboard";
                                }
                            });
                    }
                    else {
                        var mensaje_error = document.getElementById('MensajeError');
                        //$("#MensajeError").fadeTo(1000, 1);

                        //$("#MensajeError").fadeOut(5000);
                        //return false;
                    }
                }
            })
        };

CONTROLLER MVC .NET

public JsonResult Factura(string[] json)//The json parameter appears as Null
        {
            string result;
            if (json != null)
            {
                //Modify the data received json.

                result = "success";
            }
            else
            {
                result = "error";
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

Answer №1

To start, be sure to specify the parameter name where you are sending the information in your $.ajax and convert the object "data" into a JSON string.

$.ajax({
            type: "post",
            url: "/Comprobante/Factura",
            data: {json: JSON.stringify(data)},//JSON.stringify parses an object or JSON string
            dataType: 'json'
 })

Next, in your MVC controller, change the parameter type to a string and then parse the string data into the desired type.

public JsonResult Factura(string json)//The json parameter shows up as Null
    {
        string result;
        string[] data = JsonConvert.DeserializeObject<string[]>(json);
        if (data != null)
        {
            //Make changes to the received JSON data.

            result = "success";
        }
        else
        {
            result = "error";
        }

        return Json(result, JsonRequestBehavior.AllowGet);
    }

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

Guide to creating a Perl CGI script that continuously displays the current time in the browser without generating a list of times

Similar Question: Reg: Perl CGI script Autoupdate with New Data This perl CGI script continuously updates the time instead of creating a list of times. #!C:/perl/bin/perl.exe use warnings; use strict; use CGI; local $| = 1; my $cgi = new CGI; my $s ...

Struggling with parsing a JSON file in C# and looking for some guidance

I have encountered an issue while working with a JSON file in C#. { "Company": { "ABC": {"ADDRESS" : "123 STREET", "DEF" :"ADDRESS 567", }, }, "Country": { "Country1": "XYZ", ...

The overflow hidden property does not seem to be effective when used in conjunction with parallax

The issue arises when I attempt to use the overflow hidden property in combination with parallax scrolling. Although everything seems to be working correctly with JavaScript for parallax scrolling, setting the overflow to hidden does not contain the image ...

Tips for updating the content within an HTML tag with jQuery

I am looking to update the parameter value of an applet tag based on the selection from a dropdown menu. As I am new to jQuery, I would appreciate any guidance on how to achieve this using jQuery. This is my current applet code: <applet id="decisiontr ...

Sending a JSON object from JSP to JavaScript using AJAX

Is there a way to transfer JSON values from JSP to JavaScript as an object using AJAX without resorting to global JavaScript variables, which can expose the JSON content in the page's source? The desired scenario is as follows: The JSP URL is opene ...

Using jQuery to send a GET request to the current page with specified parameters

Within my application, hosted on a PHP page, I am aiming to trigger a GET request upon selecting an option from a dropdown menu. The URL of the page is: www.mydomain.it/admin/gest-prenotazioni-piazzola.php I intend to utilize jQuery to execute this GET r ...

Unable to construct React/Next project - identified page lacking a React Component as default export (context api file)

When attempting to compile my Next.js project, I encountered an error message in the terminal: Error: Build optimization failed: found page without a React Component as default export in pages/components/context/Context The file in question is utilizing ...

Errors related to missing RxJS operators are occurring in the browser, but are not showing up in Visual Studio

Recently, I encountered a peculiar problem with my Angular4 project, which is managed under Angular-CLI and utilizes the RxJS library. Upon updating the RxJS library to version 5.5.2, the project started experiencing issues with Observable operators. The s ...

Delay Export of React Component Until After Request in Shopify App Development

Being a newbie in Shopify App Development, React, and Next.js, I may have a silly question. Currently, I am making a request to a website and using the response in the React component that I want to export/render. To avoid it being undefined, I need to wai ...

Tips for sending data through an API in an AngularJS application within an Ionic framework

Being new to this field, I require some assistance. I need to send data to an API, but I am struggling with the process. Can someone please guide me on how to do this? The API link is: Below is the JSON format in which the data needs to be sent: { "er ...

How to utilize the reduce method with an array of objects in JavaScript

Every week, a number of objects are delivered to me. Each object contains information such as date, hours, and other fields. I need to arrange these objects in an array based on the total hours for each day. Here is an example of the objects: var anArray ...

What is the method for altering the color of specific columns?

I am currently testing out my Amchart with this example. Check out the working demo on code pen My goal is to modify the color of the first four columns. While I am aware that colors can be changed by specifying them in the JSON file as a property calle ...

utilize saved JSON instead of Core Data

Many tutorials explain how to retrieve JSON objects from the internet and translate them into Core Data. Currently, I am developing an iOS app (with plans for Android as well) that fetches JSON objects from the web and presents them to users. Personally, ...

Search for a particular value within a JSON file and add a suffix to it by utilizing jq

I have a json file where I need to locate a specific value and add a suffix to it within the same file. Here is the content of my json file { "apiVersion": "argoproj.io/v1alpha1", "kind": "Workflow", "met ...

After implementing JsonSerializer converters, the data retrieved from FromBody is unexpectedly null

In my .Net 6 Startup file, I included the following converters: services.AddControllersWithViews().AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DateTimeConverterFactory()); options.JsonSeri ...

Creating a callback function in Rails after an AJAX request is completed

Hello, I have a question regarding where to write a callback function after an ajax request is completed. Currently, I am working on a Twitter app and my goal is to send an email notification when a user clicks the 'follow' button. The following ...

Nested iframes encountering difficulty locating elements within iframes

Struggling to locate an element inside an iframe that is nested within another iframe. Despite efforts, the element remains elusive. Complicating matters, the first iframe has no ID or Name. https://i.sstatic.net/kflDT.png This is the current code in use ...

How can we pass a function to a child component in Vue 2.0?

I am facing a challenge with passing a function link to the child component in Vue. Although it is functioning correctly, the code appears in HTML format. How can I enhance this? In my Vue instance, I have: app = new Vue({ ... some code data: { ...

Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when s ...

"Adding properties to objects in a map: a step-by-step guide

During my attempt to add a property within a map loop, I noticed that the update appeared to occur on a duplicate rather than the original object. MY_ARRAY.map(function(d){ d.size = DO_SOMETHING }); ...