Using the JSON parameter in C# with MVC 3

I'm facing an issue with sending JSON data from a JavaScript function to a C# method using Ajax. When I receive the data in C#, it's not being recognized as JSON. How can I resolve this issue? If I try to output the received data using Response.Write(arr) in C#, it shows up as System.string[]. My project is built on MVC 3.

C# Method

public int save(string[] arr)
            {

                SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["strConnection"].ToString());
                connection.Open();
                SqlTransaction transaction = connection.BeginTransaction();

                try
                {
                    // Truncate client_resource table
                    dtsResourceClientTableAdapters.RESOURCE_CLIENTTableAdapter table = new dtsRecursoClienteTableAdapters.RECURSO_CLIENTETabelaTableAdapter();

                    for (int j = 0; j <= 149; j++) { 
                        table.Insert(arr);
                    }

                    transaction.Commit();
                    return 1;
                }
                catch (SqlException ex)
                {
                    try
                    {
                        transaction.Rollback();
                        return 0;
                    }
                    catch (Exception exRollback)
                    {
                        return 0;
                    }  
                }

            }

JavaScript Function + Ajax

$("#btnSave").on("click", function () {
        var confirmSave = confirm("Do you want to save the data?");
        if (confirmSave) {
            var list = jQuery("#resourceTable").getDataIDs();
            var totalItems = list.length;
            var arr = [];
            for (var i = 1; i <= list.length; i++) {
                var rowData = $("#resourceTable").jqGrid('getRowData', i);

                if (rowData.CD_CLIENT != 0) {
                    arr[i - 1] = {
                        col1: rowData.CD_RESOURCE,
                        col2: rowData.NAME_RESOURCE,
                        col3: rowData.CD_CLIENT,
                        col4: rowData.EMAIL_LIST,
                        col5: rowData.COPIED_EMAIL_LIST
                    }
                }
            }

            $.ajax({
                type: 'POST',
                url: '/Pages/save',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(arr),
                dataType: 'json',
                success: function (data) {
                    if (data == 0) {
                        alert("Unable to save the data");
                    }
                }
            });
        }
    });

Answer №1

Consider trying this method:

$.ajax({
            type: 'POST',
            url: '/Pages/save',
            contentType: "application/json; charset=utf-8",
            data: arr,
            dataType: 'json',
            traditional: true, --> use the conventional object serialization for the array
            success: function (data) {
                if (data == 0) {
                    alert("Unable to save the data");
                }
            }
        });

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

Partial View in MVC not displayed

When I click on a row in the table, I am attempting to load partial views using an Ajax call. The controller is correctly being called and returning the appropriate object. However, the view does not display that anything has been loaded. View <scrip ...

A guide on executing multiple Post Requests in Node.js

Currently, I am facing some issues with my code while attempting to make multiple post requests based on certain conditions. The goal is to retrieve data from an online database (Firebase), save it locally, and then delete the online data. Here's wha ...

"Enhance your online shopping experience with the dynamic 'Add to Cart' feature integrated into

I recently discovered DataTables and found it to be incredibly helpful with its built-in pagination and item display options. However, I encountered a challenge when trying to add a "Add to Cart" button at the end of the table. My goal is to use AJAX to ad ...

Utilize the atan2() function to rotate a div so that it follows the movement of the mouse

I am trying to create an effect where the mouse aligns with the top of a div and the div rotates as the mouse moves. The rotation should happen when the top part of the div is in line with the mouse cursor. My goal is to achieve this using the atan2 functi ...

Tips for automatically choosing several choices from a multiple-select using Chosen.JS

I am struggling to programmatically select multiple values in a multiple select using chosenJS/chosen.js while still ensuring that the selected values are bound to my ng-model (angularJS). In this scenario, I have a list of users, some of whom are already ...

Using jQuery checkboxes with ajax for data submission and storage in PHP without the need for insertion

Seeking guidance on how to properly serialize elements value instead of pushing it, as I am encountering an issue where each value is being inserted into the database 9 times. Any assistance in figuring out this problem would be highly appreciated. The HT ...

Generate a request to load JSON data

On my webpage, I have several external JSON files that need to be loaded. I'm looking for a way to specify the order in which they should be loaded. Using JavaScript for this task, here is an example: const func1 = () => { $.getJSON(json1, re ...

Are asynchronous promises thenable for chaining?

Can someone explain to me how asynchronous chaining works with thenable? I am new to using promises in Node.js and I am a bit confused about the concept. In the code example provided below, it seems like the promise returned from the previous Promise.the ...

Getting JSON in Codeigniter's Controller

Injecting JSON data into the controller: $.post('xyz_controller/my_function', {url:"dummy data"}, function(data) { alert("Request successful!"); }, 'json'); Upon reaching my controller's function (my_function), I ...

What is the reason behind utilising actual code in this test while employing RhinoMocks?

Looking for some guidance with this test scenario: Creating a mock of the IUnityContainer and setting up the expected return value for the IsRegistered method call. I'm encountering an Exception: Test method CommonInitializerTest.CommonInitializer_ ...

Using WEBGL to Showcase Your Images: A Step-by-Step Guide

I'm hoping to effortlessly showcase an image on the canvas at specific x and y co-ordinates using WEBGL, but I'm unsure of the process. Must shaders be included along with all other technical details? I've come across code snippets for displ ...

The system is unable to convert data of type org.json.JSONObject to a JSONArray

Here is my response: { "status": "success", "statuscode": 200, "message": "Record found successfully.", "data": { "tangible_benefits": "ds1351gsghsdh353535535", "intangible_benefits": "shwryw24y43rwehdg135313513", " ...

Is it possible to condense the coding of a vast array of objects into a more concise format?

Currently working on a personal project in react.js and aiming to write cleaner code. Is there a way to condense this code into just two lines or something similar? I attempted to create objects of arrays like const apps= {app_name:['Maps',&apo ...

The endpoint successfully responds with a 302 status code when using an AJAX-enabled class-based

I've been experimenting with implementing login and logout forms using ajax in django. My goal is to encapsulate the standard auth login and logout functionality into an ajax-enabled class-based view. The GET request is working fine, but for some reas ...

I encountered a KeyError while trying to process a JSON file that I extracted

After extracting a JSON from a website, I encountered a KeyError while trying to loop through it. The loop is as long as the JSON, so I'm puzzled about what could be causing this error. Any insights on this issue? import requests from bs4 import Beaut ...

What is the most efficient way to combine a parameter string within a JavaScript function and append it to an HTML string?

Welcome to my HTML code snippet! <div id="content"></div> Afterwards, I add an input to #content: $( document ).ready(function() { // Handler for .ready() called. var parameter = "<p>Hello</p>"; $("#content").appe ...

ensure that mocha does not consistently skip tests

When working with mocha, I include several unit tests that incorporate the skip it.skip('login (return photo)', function(done) { ... At times, I need to prevent skipping certain tests, such as right before a deployment. Is there a specific flag ...

Retrieve the value of the second child element in a table cell when clicking on it with Javascript

I have created a table with one row that includes the title of the month and a cell containing an inner table with multiple rows and cells. I want to display the content of the second cell in the second table as a modal box or alert dialog when it is click ...

React HTML ignore line break variable is a feature that allows developers to

Can you help me with adding a line break between two variables that will be displayed properly in my HTML output? I'm trying to create an object with a single description attribute using two text variables, and I need them to be separated by a line b ...

Struggling to Create a Survey with Included Message: Error - Unable to Initialize MessageEmbed

I'm attempting to create a poll feature for my discord bot that displays both the poll question and results as an embedded message. While I've managed to get the poll information in plain text format, I'm encountering an error when trying to ...