What is the best way to send JSON data to a code behind method instead of a Webmethod?

I have a dilemma with handling JSON data in my code behind to bind it to an obout grid. While I am aware of passing data using the <WebMethod>, I've encountered limitations as the method is static, making it difficult to bind the data to any grid control.

My current approach involves calling a code behind method from JavaScript and passing the data as a parameter to the method. How can this be achieved effectively?

 users = [];
 for (var i = 0; i < usersInfo.length; i++) {
          user = {
                   UserName : usersInfo[i].UserName,
                   Email : usersInfo[i].Email,
                   Status : status
          };

          users.push(user);
    }
    var results = "";
    $('#lblError').val('');
    if (users.length > 0) {
        //Need to find a way to pass the `users` data to ShowResults code behind method.
     }

Code Behind

public void ShowResults(List<UsersInfo> users)
{
       oboutGrid.DataSource = users;
       oboutGrid.DataBind();
}

public partial class UsersInfo
{
    public string UserName { get; set; }
    public string Email { get; set; }        
    public string Status { get; set; }
}

Answer №1

To add JSON data to an aspx form, one method is to insert a concealed field on the page.

<asp:HiddenField ID="jsonDataHolder" ClientIDMode="Static" runat="server"/>

Within this hidden field, input your JSON data as a string by using JSON.stringify.

$('#jsonDataHolder').val(JSON.stringify({ id: 1, name: "Sophia" }));

Subsequently, when the page undergoes a regular postback, retrieve the hidden field, deserialize it, and execute your code accordingly.

protected void btn_ProcessPostBack_Click(object sender, EventArgs e)
{
    string info = this.jsonDataHolder.Value;
    // deserialize json, perform operations
}

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

Localization of date picker in material-table(Material UI)

Does anyone have experience with localizing the date picker in material-table (Material UI)? The date picker is specifically used for filtering in this scenario. import React from 'react'; import MaterialTable from 'material-table'; fu ...

"Trouble with Angular's http.get method failing to retrieve data from MySQL through Node

I am struggling to retrieve data from MySQL using Angular and Node.js. Despite trying, I am unable to make it work. When I check Postman using the link http://localhost:8080/locations, I can see the data. { "status": "200", "items": [ { "cit ...

A guide to formatting a JSON file with single quotes using jq for a cleaner output

{ 'abc': { 'title': 'James', 'location': 'Australia' }, 'xyz': { 'title': 'Michael', 'location': 'New Zealand' } } ...

Show the value of a JavaScript object in VueJS

New to Vue and need some guidance... I'm having trouble accessing the values in a JS object displayed in the DevTools within one of my routes in a Vue app. Specifically, how can I display the values from filteredData:Array[1]? https://i.sstatic.net/ ...

SailsJS failing to detect changes in local JSON file

https://i.stack.imgur.com/RG13Y.png This sailsjs application does not utilize any database. Instead, it relies on multiple JSON files located in the data folder within the root directory. The controller accesses this data as follows: req.session.categori ...

Utilize the assigned value of a variable from a separate file

Is it possible to set a variable in an external file called "Variable.js", assign it a value in a file named "Page1.html", and then use that variable with its assigned value in another file named "Page2.html"? For example, let's consider the contents ...

Step-by-step guide to creating a transition effect when the input changes

I'm looking to add a unique effect to my dropdown menu My goal is to create an effect in which the placeholder moves up and the new value seamlessly takes its place, using JS, jQuery, CSS, and HTML. View before transition View after transition ...

How can AngularJS ng-repeat be used to extract HTML elements?

I need help parsing HTML that is received from the server as a string. Here is an example of what I receive: <img src="http://gravatar.com/avatar/9a52267d32ad2aaa4a8c2c45b83396e5?d=mm&amp;s=&amp;r=G" class=" user-1-avatar avatar- photo" width=" ...

How to dynamically increase vote tallies with React.js

The voting system code below is functioning well, displaying results upon page load. However, I am facing an issue where each user's vote needs to be updated whenever the Get Vote Count button is clicked. In the backend, there is a PHP code snippet ...

Field for user input featuring a button to remove the entry

I am attempting to add a close icon to a bootstrap 3 input field, positioned on the top right of the input. Here is what I have tried so far: https://jsfiddle.net/8konLjur/ However, there are two issues with this approach: The placement of the × ...

Classify JavaScript Array Elements based on their Value

Organize array items in JavaScript based on their values If you have a JSON object similar to the following: [ { prNumber: 20000401, text: 'foo' }, { prNumber: 20000402, text: 'bar' }, { prNumber: 2000040 ...

Executing a get request in Backbone without using the Option parameter by implementing the beforeSend method

After gathering insights from the responses to this and this queries, I have formulated the code below for a GET request: var setHeader = function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa($rootScope.login.Gebruikersnaam + ":" + $r ...

Methods for reloading the requirejs module

There are two modules: settingmap.js var settingMap = { scWidth : [4000, 6000, 8000], scHeight : [5000, 7000, 9000], bxWidth : [100, 90, 80], bxHeight : [100, 90, 80], totalTime : [50, 40, 30], level : [1, 2, 3], boxColor : [&a ...

Received an undefined response from jQuery Ajax request to a webservice

I'm facing a small issue with my webservice call. I've thoroughly debugged it and confirmed that the webservice is being called with the correct value and returning the expected result. However, when I check the alert message in the completed fun ...

Revalidating doesn't seem to work as expected in Next JS

Reviewing my code on the development server function Home(props) { console.log("Hello") return ( <ul> {props.user.map((user) => ( <li key={user.id}>{user.email}</li> ))} </ul> ) } expo ...

Rails routing issue, action being bypassed

Something strange is happening with my Rails application. It appears that the specific Action is being skipped in one environment, while working fine in another. In the development environment, everything runs smoothly and the action is executed. However, ...

What is the best way to conceal a div element on a Razor Page depending on the user's input?

How can I display the state field only when the user selects United States in the country field, and hide it otherwise? Here is the code snippet from my cshtml page: <div class="form-group col-sm-4 mt-4"> <label asp-for="Form.Co ...

Identifying rectangular shapes in an image and overlaying a div on top using Jquery

I am currently exploring the possibility of achieving the following: Imagine having an image within a div (serving as the background image). This image resembles an Excel sheet. My goal is to generate an input tag or contenteditable div when a user clicks ...

Exclude certain packages from being processed in webpack

After setting up my webpack configuration, everything was running smoothly with the specified packages in the package.json: { "peerDependencies": { "react": "16.13.1", "react-dom": "16.13.1", ...

Angular is encountering an issue where it is unable to read the value of a JavaScript function, despite the object having a value

I have developed some JavaScript functions that involve reading and writing to a JSON file, with the intention of calling them in an Angular environment (from TypeScript code) using the jsonfile library. Below is the code snippet: function savePatient(pa ...