Issue with Gijgo grid not updating properly during change event

I'm currently working on an MVC 5 application and I've hit a roadblock with a particular view. This view contains a dropdown menu and a grid (Gijgo-grid). The grid's content is supposed to change based on the selected value from the dropdown. However, when I select a different option from the dropdown after the initial selection, the grid fails to update.

For the onchange event of the dropdown, I have implemented an ajax call to trigger a function in the controller that fetches data for the grid.

The cshtml page structure is as follows:

<div>
      <table id="gridmvc"></table>
</div>
<script>
$(document).ready(function(){
  $("#DropDownID").change(function(){
      $.ajax({
         type: 'POST',
         url : '/Test/GetGrid',
         data: {selectedID: this.value},
         success: function(data){
            grid = $('#gridmvc').grid({
                 primaryKey: 'DeliveryID',
                 dataSource: data,
                 columns: [
                      {field: 'DeliveryID'},
                      {field: 'ProductName', sortable: true},
                      {field: 'Amount', sortable: true}
                 ],
                 pager:{limit: 5}
            });
         },
         error: function(){alert('error');}
      });
  });
});
</script>

Here is the relevant functionality in the Test controller:

public JsonResult GetGrid(int? page, int? limit, string sortBy, string direction, int selectedID)
        {
            List<ViewModel> records;
            int total;

                var query = Lync query to fetch data from Database using selectedID;

                if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
                {
                    //code for sorting
                }
                else
                {
                    query = query.OrderBy(q => q.DeliveryID);
                }

                if (page.HasValue && limit.HasValue)
                {
                    //code for paging
                }
                else
                {
                    records = query.ToList();
                }

            return this.Json(records, JsonRequestBehavior.AllowGet);
        }

The goal is to ensure that the grid data refreshes accurately based on the new dropdown selection.

Answer №1

Documentation reveals the presence of a reload function.

Check out the documentation here

The Reload function essentially refreshes the data in the grid from a data source. You can modify the datasource and trigger a reload based on specific parameters as shown below:

<script>
    //RAZOR view    
    function reloadGrid(){  
            grid.clear();
            grid.reload();
    }

    $(document).ready(function(){
      $("#DropDownID").change(function(){
                grid = $('#gridmvc').grid({
                     dataSource: '/Test/GetGrid'
                     params: { selectedID: this.value },
                     primaryKey: 'DeliveryID',
                     columns: [
                          {field: 'DeliveryID'},
                          {field: 'ProductName', sortable: true},
                          {field: 'Amount', sortable: true}
                     ],
                     pager:{limit: 5}
                });
                reloadGrid();      
      });
    });
</script>

In case you need to alter the data during an Ajax call, utilize the render function.

Further details on render function are available here

The Render function displays data in the grid (based on your response).

Hence, for success responses, implement this:

<script>
$(document).ready(function(){
  $("#DropDownID").change(function(){
      $.ajax({
         type: 'POST',
         url : '/Test/GetGrid',
         data: {selectedID: this.value},
         success: function(data){
            grid = $('#gridmvc').grid({
                 primaryKey: 'DeliveryID',
                 columns: [
                      {field: 'DeliveryID'},
                      {field: 'ProductName', sortable: true},
                      {field: 'Amount', sortable: true}
                 ],
                 pager:{limit: 5}
            });

            grid.render(data);
         },
         error: function(){alert('error');}
      });
  });
});
</script>

Additionally, insights from gijgo.js mention Line 4554:

Access gijgo.js file here

This line specifies the parameters object containing details to be sent to the server.

Answer №2

Requesting Grid Data and Dropdown Selection Separately

<script>

var grid;
var url = '/Test/GetGrid';

$(document).ready(function(){

grid = $('#gridmvc').grid({
       primaryKey: 'DeliveryID',
       dataSource: url,
       params: { selectedID: $("#DropDownID").val() },
       columns: [
           {field: 'DeliveryID'},
           {field: 'ProductName', sortable: true},
           {field: 'Amount', sortable: true}
        ],
        pager:{limit: 5}
});


$("#DropDownID").change(function() {
   grid.reLoad( { selectedID: $(this).val() } );
});

</script>

Test Controller 
.
.
public JsonResult(int? page, int? limit, int? selectedIDpersonId)
{  
   long total = ....
   .......
   return this.Json(new { records, total }, 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

Steps to displaying the result

new Vue({ data: { folders : [{ name : 'folder1', isActive : 1, }, { name : 'folder2', isActive : 0, }, ] } } }) Is there a way to access the active val ...

"Trouble with MongoDB aggregate query: Adding a new stage to pipeline leads to zero

Running an aggregate query through PyMongo and encountering some unexpected results. The MongoDB aggregate query looks like this: [{ $match: { syscode: { $in: [598.0] }, date: { $gte: newDate(1509487200 ...

Resize the main container to fit the floated elements

I've been working on constructing a family tree, and the last part of the functionality is proving to be quite challenging for me. My family tree consists of list elements that are all floated to the left. Currently, when the tree expands beyond the ...

Using Angular to bind the ngModel to a variable's object property

In my application, I am working with a user object that looks like this: let user = {name: "John", dob:"1995-10-15", metadata: {}} The metadata property of the user object is initially empty. I want to add a new property to the metadata object based on u ...

Is it unnecessary to mention both JavaScript and AJAX together?

During a recent conversation I had, someone mentioned that it is inaccurate to state that since Ajax is JavaScript. The scenario was: "How can I perform an action on a webpage without requiring a page refresh?" My response: "Utilize JavaScript along wi ...

Utilizing Angular 1.4.8 and lodash to effectively parse an array of objects with conditional parameters

DEVELOPER TOOLS Angular version 1.4.8, lodash version 4.0 SOLUTION IMPLEMENTATION After building on Derek's code contribution below, I have arrived at the following solution. It was necessary to make adjustments as using _.property() or _.map() ch ...

Leveraging periods within a MySQL database: Node.js for seamless updates

I am currently facing a challenge in updating a column name that contains a period in node using node-mysql. I appreciate the convenience of being able to update multiple columns by providing an object with keys, but the string escaping process with node-m ...

Cloud function -> time stamps evaluation

I've been working on a cloud function to delete items in the "links" collection that have an end time older than the current timestamp. Although my function runs without any errors, it's not deleting the items as expected and is causing me quite ...

Navigate to the same destination with React Router Dom while passing state as a parameter

Let's talk about a scenario with a Link setup like this: <Link to={`/samelocation/${id}`} state={{ state1: 'hello' }}> This link is nested in a sub-component within the main component situated at /samelocation/:id. To ensure that the ...

How to troubleshoot passing json data from a controller to an AngularJS directive

I recently started learning AngularJS and I'm facing an issue with passing JSON data from the controller to a directive. When I try to display the data, nothing shows up and I encounter the following errors: 1. Uncaught SyntaxError: Unexpected token ...

Is there a way to implement absolute imports in both Storybook and Next.js?

Within my .storybook/main.js file, I've included the following webpack configuration: webpackFinal: async (config) => { config.resolve.modules = [ ...(config.resolve.modules || []), path.resolve(__dirname), ]; return ...

The issue with the smooth scrolling feature in next/link has not been resolved

I am currently facing an issue where smooth scrolling is not working when using next/Link, but it works perfectly fine with anchor tags. However, the downside of using anchor tags is that the page reloads each time, whereas next/link does not reload the pa ...

utilizing an ajax request to clear the contents of the div

When I click on Link1 Button, I want to use ajax to empty the contents in the products_list div <button type="w3-button">Link1</button> I need help with creating an ajax call that will clear the products in the product_list when the link1 but ...

What is the method for sending arguments to material avatar using require?

import Avatar from '@material-ui/core/Avatar'; Here is an example of working code: <Avatar alt="user 4" src={require('Assets/img/user-1.jpg')} className="size-80 rounded-circle border-info rct-notify" /> However, I encountered ...

Is there a way to retrieve two distinct values from an object?

Is there a way to retrieve two target values from an option using useState in react/nextjs? Here is a sample of my api: const movies = [ { id: 1, name: "Fight Club" }, { id: 2, name: "Titanic" }, { ...

Maintain the value of `this` using a recursive setImmediate() function

Hey there! I'm working on a node.js app where I need to utilize setImmediate() to recursively call a function while maintaining its context for the next iteration. Let's take a look at an example: var i=3; function myFunc(){ console.log(i ...

What is the best way to test a component that displays its children elements?

I am encountering an issue with testing the functionality of a component I have created. The component is a Button that accepts props such as className, children, and otherProps. export default function Button({ className, children, ...otherProps }) { r ...

Using Express middleware in a TypeScript Express application

I'm currently converting the backend of an ExpressJS application to Typescript. While working on the auth.routes.ts file, I encountered an issue with the middleware (authMiddleware). It seems like there might be a typing error, as the same code in the ...

Update the state of the parent component based on changes made in the child component (both are functional

Here is the layout for the current issue: . ├── components │ ├── ModalPolicy.js │ ├── Footer │ ├── index.js ├── pages │ ├── index.js I attempted to display the Modal on Footer/index.js but it did no ...

Tips for sending a JSONObject type value in Java through Postman

Here is my Java DTO class: public class fieldProviderDTO { private JSONObject information; public JSONObject getInformation() { return information; } public void setInformation(JSONObject information) { this.information = infor ...