Utilizing LINQ with a list of AJAX elements for seamless integration with DataTable

Trying to execute a LINQ query to populate an AJAX list, which will then be used in a DataTable within my View.

This was previously working without any issues when I wasn't using AJAX. The data was directly placed in the model and each row was rendered in a loop. However, this method was very resource-intensive and resulted in slow rendering times for larger queries.

Switching to AJAX, the LINQ query started returning NULL. I have confirmed that data retrieval works fine by implementing a test case with a small sample of AJAX. Nevertheless, the data table does not get populated for some reason.

In short, what I need: Fix the LINQ to List conversion and use it to fill the DataTable.

Below is the controller code:

(controller code here)

And here is the JavaScript code in the View:

(JavaScript code here)

and here is the DataTable section in the View:

(DataTable code here)

Some functions that are not essential for understanding have been omitted.

Thank you for your assistance.

EDIT: Another important point is that the success or failure functions of my datatable are not being executed.

EDIT: I removed the ViewData implementation, and now everything works (tested in POSTMAN)! However, when trying to fetch all data, it exceeds the maximum JSON limit: 2147483644.

Attempting a smaller query, which displays correctly in POSTMAN but doesn't show up in the table, resulting in an error:

http://localhost:51326/Table/Index?draw=1&columns%5B0%5D%5Bdata%5D=0&column…art=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1480633376897 Failed to load resource: the server responded with a status of 404 (Not Found)

Currently working on resolving this issue.

Answer №1

Modified function (excluding dropdown population and DataView operations, which are part of a separate function):

public List<stockAJAX> getList(string selectedGroupType, string selectedList, string selectedAmount)
{
    using (TableEntities context = new TableEntities())
    {
        // Initialize base query
        IQueryable<stock> stocks = context.stocks.AsQueryable();

        // Filtering logic
        if (selectedList == null && selectedGroupType == null)
        {
          // Return all records
        }
        else if (selectedGroupType == "grouptype=Select+GroupType" || selectedGroupType == null || selectedGroupType == "") 
        {
            if (selectedList == null || selectedList == "")
            {
              // Return all records
            }
            else
            {
                stocks = stocks.Where(c=>c.ProductGroup == selectedList);
            }
        }
        else if (selectedList == "list=Select+Company" || selectedList == null || selectedList == "")       
        {
            stocks = stocks.Where(c=>c.GroupType == selectedGroupType);
        }
        else
        {
            stocks = stocks
              .Where(c=>c.ProductGroup == selectedList)
              .Where(c=>c.GroupType == selectedGroupType);
        }

      // Limit data results
      if (selectedAmount != "true") 
      {
        stocks = stocks
          .OrderByDescending(c=>c.DateArrived)
          .Take(1000);
      }

      // Project to DTO
      var result = stocks.Select(c=>new stockAJAX
      {
        StockId = c.StockId,
        ProductGroup = c.ProductGroup,
        GroupType = c.GroupType,
        ItemType = c.ItemType,
        Model = c.Model,
        SerialNo = c.SerialNo,
        NR = c.NR,
        Status = c.Status.ToString(),
        Description = c.Description,
        DateArrived = c.DateArrived.ToString(),
        CurrentLocation = c.CurrentLocation,
        TerminalId = c.TerminalId,
      }).ToList();
    }

    // Return values for DataTable use
    return result;
}

Answer №2

I was able to resolve the issue by following the suggestion to remove references to the ViewData.

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult getAJAX()
        {
            using (TableEntities context = new TableEntities())
            {
                stock = (from c in context.stocks
                         select new stockAJAX
                         {
                             StockId = c.StockId,
                             ProductGroup = c.ProductGroup,
                             GroupType = c.GroupType,
                             ItemType = c.ItemType,
                             Model = c.Model,
                             SerialNo = c.SerialNo,
                             NR = c.NR,
                             Status = c.Status.ToString(),
                             Description = c.Description,
                             DateArrived = c.DateArrived.ToString(),
                             CurrentLocation = c.CurrentLocation,
                             TerminalId = c.TerminalId,
                         }
                                    ).Take(1000).ToList();
            }

            return Json(stock, JsonRequestBehavior.AllowGet);
        }

However, I encountered a new issue where the DataTable is now stuck on "Processing". For more details, please refer to the question posted here: Datatable stuck on "Processing" on initial load

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

What could be causing my jQuery to not retrieve the value of the <select> element?

Here's a snippet from my index.html file: <body> <select id="car"> <option value="TOYOTA">TOYOTA</option> <option value="BMW">BMW</option> </select> <input type=button id="get_btn" valu ...

Best practices for setting an array as a state value in ReactJS

I've been facing challenges while trying to retrieve user information from an array of objects using the fetch API. Despite attempts with constructors, functions, and binding methods, I couldn't get the desired results. Even using ComponentDidMou ...

Creating a semi-circle donut chart with Highcharts using the Highcharts-ng library

I have been working on integrating a Highcharts Semi-circle donut chart into my angular application using the Highcharts-ng directive. However, I seem to be facing an issue where the plotOptions section is being skipped entirely, leading to a full circle p ...

tips on locating the next immediate downloadable cell in a table

My table includes cells with colspan and rowspan attributes. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table border=1 id="mytable" > <tr><td>A1</td> <td> A2 < ...

Leveraging the power of BigCommerce API with PHP AJAX to enhance cart functionality for accurate

My goal is to provide customers with the option to view product weights in their cart. To achieve this, I am incorporating an external JS file into the cart template on BigCommerce: storefront: https://store-xxx.mybigcommerce.com/cart.php or backend temp ...

Import a file using Selenium and manipulate its contents

I'm currently working on a Selenium test that involves uploading a file via an OpenFileDialog window. Typically, I use the SendKeys function to accomplish this task. However, in this specific scenario, simply using SendKeys is not sufficient. The iss ...

HTML table containing radio buttons styled with Font Awesome icons

I'm having some trouble getting a radio button with Font Awesome to work properly within an HTML table. Outside of the table, it functions as expected, but inside the table, it only seems to hide/show between the two states without displaying the chec ...

Challenges faced with Vuetify's vertical and non-linear stepper components

I've been struggling to grasp the concept of Vuetify's stepper feature. Despite my efforts, I haven't been successful in combining different steppers from their page that each have elements I need but lack others. One example is this one on ...

What is the reason behind a PHP page refresh causing a session variable to be released

In an attempt to unset a session variable after 2 minutes using unsetsession.php, I have the following code: <?php session_start(); if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120 ...

What is the best way to extend the page load timeout for the Selenium Chrome driver?

My current setup involves using the Chrome driver to upload files to a remote server, which can sometimes take more than 30 minutes. In order to accommodate this, I have set the page load timeout value as shown below. driver.Manage().Timeouts().PageLoad = ...

Issue encountered while serializing data in next.js when utilizing getServerSideProps function

Encountering An Error Error: The error message "Error serializing .myBlogs returned from getServerSideProps in "/blog"" keeps popping up. I'm facing a problem while attempting to log the data! Initially, when I was fetching data using use ...

What methods can be used to troubleshoot an issue of an AngularJS function not being called

I am facing an issue with a dynamic table I have created. The rows and action buttons are generated dynamically when the user clicks on the Devices accordion. However, there seems to be a problem with the function expandCollapseCurrent(). Whenever the use ...

streaming a silverlight video on the webpage

I've been doing some research and I'm unsure about the best way to have a video file on my server play on an ASPX web page using .NET 4. What format should I use to store the video file? Perhaps WMV? I found a snippet online that uses Silverligh ...

Animate or resize with a focal point

Seeking suggestions on how to create an animation effect for changing the width and height of a div from the top center. I experimented with using effect('scale'), but it reverts back after completion due to being based on show/hide actions. I t ...

The functionality of jQuery's checked length is not operating as expected

Is it possible to check if two checkboxes are selected and then enable other checkboxes without accessing the HTML? Any advice would be greatly appreciated as this seems like a simple issue. Check out the code snippet below: //disabling checkboxes on l ...

Top approach for receiving real-time json data in laravel

I am currently working on integrating the jquery.mentionsInput component into my Laravel application. This will allow users to @ mention other users in comment sections of a thread. My goal is to only fetch users who have posted in that specific thread, ...

Having trouble getting PHP Ajax File Upload to function properly?

I am using Bootstrap and have a Form in a Modalbox. There is a Fileupload field, and I want to upload images. However, when I click the Submit button, the site seems to reload instantly and there is no file uploading... Below is my Ajax Script: <scri ...

"Successfully making AJAX calls on localhost, but encountering issues when trying to make them online

Whenever a visitor navigates to a specific page (referred to as page1), the PHP script is initiated to load the HTML content for an array that contains data about the users. After the page has finished loading (DOM ready), I utilize jQuery to make an AJAX ...

The XML content fails to display after initiating an AJAX request

Attempting to create an ajax call and accessing a field from the table on the server yields the following: <PushProperty><Status ID = "1"> Success </Status><ResponseID> b3633c9eeb13498f </ResponseID><ID> 9098 & ...

Codeigniter 3 - Troubleshooting Ajax Image Upload Issue

Hey there! I'm currently working with Codeigniter 3 and jQuery ajax. Utilizing the built-in upload library... I'm attempting to upload an image to my server, but consistently encountering this error message: You did not select a file to uplo ...