What is the best way to retrieve my chosen GridView rows and store them in a JavaScript variable?

Using ASP.NET C# MVC3 with razor templates, I have a question:

In my DevExpress GridView, I can select rows. How can I pass the selected rows into a JavaScript variable? Also, if I select multiple rows simultaneously, is there a way to get them in an array?

Edit: Thanks to a comment, I now have the following 'JQuery' function:

$(function () { // Delete function
    $('#select').click(function () {
        var Delete = confirm("Are you sure you want to delete the selected records?");
        if (Delete) {
            // Delete Function
            var test = ;
            alert(test);
        } else {
            // Nothing
        }
    });
});

I am trying to retrieve the Id of the selected rows and store it in the variable 'test'. I attempted to use GetSelectedFieldValuesCallback and GetSelectedFieldValues, but it is not working as expected. If anyone has an example they could provide, I would greatly appreciate it.

Answer №1

One of the most fundamental operations of a grid seems to be lacking in examples, especially when it comes to sending rows back to the server for further processing.

The issue with using grid.GetSelectedFieldValues() is that it triggers a postback, requiring an additional postback to actually send the data back to the server.

A more elegant solution I discovered is to utilize grid.GetSelectedKeysOnPage(), which returns selected key fields as defined by settings.KeyFieldName = "Id".

This code snippet showcases how to set up your grid:

<script type="text/javascript">
    $(function () {
        $('#btn1').click(function () {
            simpleGrid.PerformCallback();
        });
    });

    function OnBeginCallback(s, e) {
        var selectedValues = s.GetSelectedKeysOnPage();
        e.customArgs["Id"] = "";
        for (var i = 0; i < selectedValues.length; i++) {
            e.customArgs["Id"] += selectedValues[i] + ',';
        }
    }
</script>

@Html.Partial("ProductsPartial", Model.Data)

<div id="btn1">
    btn
</div>

It's recommended to create your grid in a separate partial view, per the DevExpress documentation.

The "ProductsPartial" partial view structure is as follows:

@Html.DevExpress().GridView(
        settings =>
        {
            settings.Name = "simpleGrid";
            settings.KeyFieldName = "Id";
            // Additional settings and configuration options here 
        }).Bind(Model).GetHtml()

Lastly, you can process the data on the server side within your controller action:

public ActionResult Postback()
{
    String data = Request["Id"];
    // Process the data here
}

This approach allows for efficient server-side data processing.

Answer №2

I have discovered the solution I was seeking. The function below contains the necessary data:

$(function () {
    $('#select').click(function () {
        Grid.GetSelectedFieldValues("Id", OnGetSelectedFieldValues);
    });
});

function OnGetSelectedFieldValues(result) {
    for (var i = 0; i < result.length; i++){
            alert(result[i]);
        }
}

This information is valuable for individuals facing similar challenges.

Replace "Grid" in

Grid.GetSelectedFieldValues("Id", OnGetSelectedFieldValues); 

with the name of your gridview, and modify "Id" according to the desired column value.

You can retrieve multiple data elements from a single row by adding another loop inside the

function OnGetSelectedFieldValues(result)
like this:

function OnGetSelectedFieldValues(result) {
    for (var i = 0; i < result.length; i++)
        for (var j = 0; j < result[i].length; j++) 
            alert(result[i][j]);
        }
}

Don't forget to adjust the getter accordingly as well

Grid.GetSelectedFieldValues("Id;ANOTHERCOLUMN", OnGetSelectedFieldValues);

This guidance may prove beneficial to others facing similar obstacles in the future.

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

Identify the absence of search results in an Ajax request to the search page before rendering the HTML content

I am attempting to retrieve JSON code from a page using the following PHP function: private function __ajax_admin_search($username = '') { $result = $this->admin_login->Admin_Username_Ajax($username); $count = count($result); for ...

What is the reason behind the unnecessary requirement of adding {...props} when passing them to a component in a React router?

Recently, I delved into learning React and encountered a puzzling issue while following a course. To gain clarity, I decided to experiment with it separately, but the confusion remains unresolved. While researching, I discovered that when utilizing a Rout ...

XMLHttp request experiencing mixed content issues

Struggling with obtaining OAuth Tokens from a POST request through the Bungie API using javascript and XMLHttpRequest. Despite both my website and the API endpoint being secure (https), every post request I send returns a Mixed Content page error. I'v ...

Showing changes in state in real-time using ReactJS: A quick guide

Hello, I am currently facing an issue while trying to add a comment and display it immediately on the DOM. Whenever I type any word in the form box, it does not appear in the box. Additionally, pressing the enter key does not trigger a POST request. Could ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

Heroku hosting a React/Node application that serves up index.html and index.js files, with a server actively running

It seems like the issue I'm facing is related to my start scripts. After researching online, I've come across various start scripts shared by different people. Some suggest using "start": "node index.js" -> (this doesn't start my server ...

Using lazy loading and $ocLazyLoad for improved performance

Recently, I stumbled upon the $ocLazyLoad third-party Angular module that allows for the lazy loading of JavaScript files. This concept has me a bit perplexed. Can you explain the difference between lazy loading and caching, and why one would choose to l ...

How can I implement a search box on my HTML website without relying on Google Custom Search?

Greetings to all! I am currently managing a website filled with HTML content. I am looking to incorporate a search box into the site. After researching on Google, most of the results point towards using Google Custom Search. However, I require a search box ...

Navigating files using NodeJS and ExpressJS

Can NodeJS (or ExpressJS) facilitate the following task? Although I appreciate the flexibility that routing provides, I find the configuration process quite cumbersome. (I don't consider myself an expert in Express) For instance, imagine an applicat ...

Discovering the power of ng-change in an Angular typeahead search functionality

I am facing an issue with displaying the result list when searching for users on key press using customTemplate.js. The list is not showing up after the first key press. Below is the code I am using: <input type="text" placeholder="Search people here ...

Guide on triggering a bootstrap popup modal using a TypeScript file

I am currently working on an Angular project where I need to launch a popup modal when my function is called. I came across an example on w3schools, but it only contains the HTML logic to open the popup. What I want to achieve is to open the popup from th ...

Maximizing React Performance: Strategies for Avoiding Unnecessary Renderings on State Updates

I am facing a major performance issue due to constant re-rendering of my child components on every state change. I need a solution to prevent this from happening and maintain the stability of my application. Any suggestions or guidance would be highly ap ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

The rows in the React table are refusing to change color despite the styles being applied; instead, they are coming back

Hey there, Green Dev here! I've been working on a React table where I'm trying to conditionally change the row color. The styles are being passed in, but for some reason they return as undefined. Strangely enough, when I remove my logic and simpl ...

In JavaScript, ensure to directly use the value of a variable when defining an asynchronous function, rather than by reference

Hello there, Let me paint you a picture: for (j = 0; j < btnArr.length; j++) { var btn = document.createElement("button"); btn.addEventListener("click", function() { press(this, j) }, false); div.appendChild(btn); } The issue at hand is t ...

Encountering an issue with the message "SyntaxError: Unexpected token < in django-jquery-file

I am currently working on implementing django-jquery-fileupload into my project. https://github.com/sigurdga/django-jquery-file-upload However, I encounter an "Error SyntaxError: Unexpected token < " when attempting to click the "start" upload button. ...

What is the method for adding/removing the 'hidden' attribute within a <p hidden> element

What is the best way to toggle the visibility of 'hidden' in the element <p hidden>My Text</p>? I attempted removing the attribute and setting it to false, but unfortunately, neither method seemed to work. let paragraphElements = d ...

Using a JavaScript "for each" loop instead of having several "if

Could you please provide guidance on where to proceed? There are multiple input rows, with each row containing a field with the class row_changed If the value in the field is greater than 0, ajax will send the entire row to PHP. Each row is wrapped in a ...

Steady always faces in one direction

I have been working on a Three.JS scene where I need to create an open-topped cylinder with two different colors for its front and inside surfaces. To achieve this, I extended a new material class from THREE.MeshStandardMaterial and made adjustments to th ...