Sending data between Javascript and C# can be achieved by passing Javascript objects

After gathering information from a web form with Javascript on button_click, I have stored it in an object. Following this, I made an attempt to utilize Ajax and JSON to transmit the object to a method in my C# code.

Javascript:

$(document).ready(function () {
    $("#go").click(function () {
        $('#<%=gv_Rota.ClientID%>')
            .find('tr')
            .each(function (row) {
                $(this).find('select')
                    .each(function (col) {
                        $ctl = $(this)
                        if ($ctl.is('select')) { 
                            var shift = $ctl.val();
                            var day = row;
                            var wk = col + 1;
                            var objectitem = { ShiftId: shift, Day: day, Week: wk };
                            $.ajax({
                                url: '/Administration.aspx/StoreObject',
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify({ myObject: objectitem })
                            });
                        }
                    });
                });
            });
        });

C# behind:

[WebMethod]
public static void StoreObject(string[] myObject)
{

}

The Javascript function iterates over a GridView to extract the selectedvalues from DropDownLists within it. This means that the Javascript will execute multiple times, resulting in multiple objects being passed.

How can I store all these passed objects in rows of a DataTable in C#, for instance, so that they can be accessed when I click a 'Save' button? Specifically, I am unsure about what should be included in the StoreArray method, and secondly, I'm uncertain about the best approach to retain the DataTable after pressing 'Save' and triggering a PostBack, as it may get reset during this process.

Answer №1

To create a C# class that mirrors the object in your JavaScript, follow these steps:

Here is an example:

public class Item
    {
        public string Id { get; set; }
        public string Day { get; set; }
        public string Week { get; set; }
    }

Next, define a method to accept input:

[WebMethod]
public static void StoreObject(Item myObject)
{

}

Additionally, if you want to store items in a collection, you can use a list of Items like this:

 private List<Item> myList = new List<Item>();

[WebMethod]
public void StoreObject(Item myObject)
{
    myList.Add(myObject);
}

Note: The method cannot be static for this to work. WebMethods may not support static methods, so consider hosting the method on an asmx page instead. More information here

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 on providing a secondary parameter to a JavaScript function

I am currently working on a JSP that contains a JavaScript function: function validateSelection(identifier, page) { var form = ObjectId("profileForm"); form.elements['checkedLogin'].value = "" + identifier; form.elements['pageList& ...

Steps to loop through and append a new attribute to an array within a JSONata object

Within my JSON object, there is a key called policyList containing an array as its value. Inside this policyList, there exists another array labeled product. Each object within the product array includes a field called amount. I am looking to include a fl ...

Don't continue to expect other promises if one of them comes back with a special

I am dealing with a situation where I need to validate data in multiple tables by utilizing a function called validateTables(). This function relies on an asynchronous helper function queryTable() to check each table through API queries. The requirement fo ...

Utilize Nuxt.js context within a Vue plugin

I have a situation where I'm working with Nuxt.js and have two plugins set up. In order to gain access to the VueI18n instance from lang.js within validate.js, I am in need of some guidance. Is there anyone familiar with how this can be accomplished? ...

How can we ensure that paragraphs are validated correctly in a multiline Textbox using JavaScript?

Currently, I am attempting to validate text (paragraphs) in JavaScript for a multiline textbox. The requirement is that after entering text into the textbox, the very first letter should be changed to a capital letter while the rest should remain in lowerc ...

The error message "Evaluating this.props.navigation: undefined is not an object" indicates that there

In the navigation bar, I am trying to keep a touchable opacity at the top right. When this touchable opacity is pressed, I want to redirect the user to the home page. constructor(props) { super(props); this.state = { stAccntList: [], ...

struggles encountered while retrieving JSON in a React application

Forgive me if this seems too basic or if I've made a grave error. I am completely new to React and coding in general, and I am attempting to create a React application that displays recipes on cards. These cards should be dynamic and searchable, disap ...

Can you iterate through two arrays to find common values?

Upon examining my firebase database, I found the following structure: Users { askdfasdf: John: { Selection: [1,2,3] }, fasfadffe: Mark: { Selection: [1,2,4] } } Players { { name: &apos ...

Updating Array State in ReactJS: Best Practices

I have been working on implementing a tag feature using React, but I am facing challenges with updating the tags dynamically. Regarding TagsInput.js import React, { useState } from "react"; import CancelIcon from "@material-ui/icons/Cancel& ...

AngularJS Directive for Creating Dynamic Menus

I am looking to implement a custom mmenu directive in my Angular application. Currently, I have set it up and utilized link: function(){} within the directive. For more information about the jQuery Plugin, you can visit their webpage here: Below is the c ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

The error message `fablinker.php:343 Uncaught TypeError: $(...).dialog is not a function` indicates that

When attempting to call a function on click, I'm encountering an error in the console. I've researched various solutions on Stack Overflow such as checking for jQuery duplication, but haven't had success. Any suggestions? https://i.ssta ...

Refreshing jqxGrid with updated data from a different web address

I am working with a jqxGrid form the JqWidgets library and I have successfully bound the data to it. Here is my code snippet: var url = "getConsignments.php?type="+$('#selectIsDelevered').val(); var consignmentsource = { ...

Tips on submitting a form without causing a page scroll to the top

I currently have a collection of conversations which are essentially multiple messages grouped together by the sender. For each conversation, there is a designated reply text box located below it. Whenever I input some text into the reply box and hit the ...

Tips for creating a linear movement effect for a collection of objects

I am working on animating a linear gripping motion for picking and placing objects. Here is a codesandbox link where you can see the issue I am facing: https://i.sstatic.net/dUdPv.png The gripper is created, moves down to reach the LEGO brick, and then s ...

Speeding up the loading time of my background images

body { background: url(http://leona-anderson.com/wp-content/uploads/2014/10/finalbackgroundMain.png) fixed; background-size:100% auto; } I have unique background images on each of my sites, but they are large in size and take some time to load due to bein ...

Unraveling a stringified string in JAVA

I have a string that looks like this: {"version":"T2"} I retrieved this string from a webview and stored it in a variable called s. I am trying to extract the value of the 'version' key. Here is my code: try { s = s.replaceAll(" ...

Creating multiple select drop-down listboxes in PHPWould you like to learn how to make

Seeking guidance on generating select drop-down lists in PHP. The code I have written only seems to work for the first drop-down, not the second... Here is the code snippet that has been causing me trouble: <?php while($row = my ...

JQuery fails to keep up with the dynamic updates that angularjs effortlessly handles

Dealing with AngularJS has been a learning curve for me. <span data-end-time="{{ productAuctionEnd | date:'yyyy,MM,dd,HH,mm,ss' }},000" class="detail-rest-time js-time-left"></span> As I try to incorporate jQuery into the mix $(".j ...

Challenges with recursively merging PHP arrays

Encountering a problem while utilizing array_merge_recursive within a foreach loop. My goal is to scrape a website and organize the data into a multidimensional array. Below is my code snippet: Original Array $apiarray = array( "response" => array( ...