What is the best way to display data from multiple lists that are returned by a JSON function?

List of My Models:


ClassAllocate: Contains Id, DepartmentId, CourseId, RoomId, DayId, StartTime, EndTime

Course: Consists of Id, CourseCode, CourseName, DepartmentId

Room: Includes Id, RoomNumber

Day: Has Id and DayName

My goal is to search for courses by department ID from the "ClassAllocates" table on the view page and display only the schedule/allocation details for those courses.

I am utilizing JSON to send lists from the controller to the view. I am facing difficulty in sending multiple lists from a JsonResult function. Although I can send them (tried with 2 lists), I am unable to display them properly - it either shows [object Object], nothing, or undefined in my attempts.

Below, I am sharing my Controller function and JavaScript code in the view:

1st: Controller Function

 public JsonResult GetCourseIdListByDepartmentId(int departmentId)
    {
        var x = db.ClassAllocates.DistinctBy(m => m.CourseId).Where(m => m.DepartmentId == departmentId).ToList();
        var r = db.ClassAllocates.DistinctBy(m => m.RoomId).Where(m => m.DepartmentId == departmentId).ToList();
        var all = new [] {x,r}.ToList();

        return Json(all, JsonRequestBehavior.AllowGet);
    }

2nd: View JavaScript

<script>
$("#DepartmentId").change(function () {
    var dptId = $("#DepartmentId").val();
    //alert(dptId);
    $(".RowClass").empty();


    var json = {
        departmentId: dptId
    };
    $.ajax({
        type: "POST",
        url: '@Url.Action("GetCourseIdListByDepartmentId", "ClassAllocates")',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(json),
        success: function (data) {

            $.each(data, function (key, value) {

                $(".table2").append(
                        '<tr class="RowClass">' +
                        '<td>' + value.Couse + '</td>'

                        + '<tr>');
                });
        }
    });
});

The current output displays as: undefined

I specifically require CourseCode, CourseName, and RoomNumber to be displayed.

Answer №1

After receiving JSON data in the form of a List or list, I find myself needing to iterate through it twice in my View code or on the client side to process the information.

$.each(data, function (key, value) {
                if (key==0) {
                    $.each(this, function (k, v) {
                        $(".table2").append(
                            '<tr class="RowClass">' +
                            '<td>' + v.Course.CourseCode + '</td>'

                            + '<tr>');
                    });
                }

                });

Now, I am faced with the challenge of handling more complex data.

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

Exploring Nested JSON Iteration in Angular4

I am struggling to iterate through a nested JSON and extract the desired output. Can someone assist me in retrieving the bpmn:startEvent id value from the JSON provided below? { "bpmn:definitions":{ "@attributes":{ "xmlns:xsi":"h ...

Using Axios to Integrate an API - Displaying a Username and Password Pop-up

I have been given a project that involves API integration. I have successfully retrieved data from the API, but there is a pop-up appearing asking for a username and password. Although I have these credentials, I would like to log in without that pop-up ap ...

Deciphering numerical elements within Perl's JSON parsing capabilities

My task involves parsing a JSON structure with an element name that is unknown. Typically, I would access the data in this manner. my $layer1 = $responselayer->{'data'}; my $layer2 = $layer2->{'123'}; my $layer3 = $layer3->{& ...

Compare the current return value to the previous value in the success callback of an Ajax request

I am currently running an Ajax request to a PHP DB script every 3 seconds, and I need to make a decision based on the result returned. The result is a timestamp. Let's say the ajax request is fired two times. I want to compare the first result with th ...

"Exploring the New Features of Bootstrap 5: Button Collapse and

I am struggling to get two buttons working with Bootstrap 5. The first button is supposed to trigger two JavaScript functions to open a bootstrap carousel. The second button is a simple collapse button designed to reveal a long text string. Unfortunately, ...

Encountered an error while attempting to load resource in Node.js

I'm currently working on a project utilizing Node js (Express...). Let me do my best to explain the issue I am encountering. My work is being done on localhost, and the main page of my index.html has buttons that lead to other pages when clicked. I c ...

Can metrics/tracing be instrumented in a .NET library to support both Prometheus and application insights simultaneously?

I am currently in the process of developing internal libraries for my company, with the goal of integrating metrics and tracing functionalities for both Prometheus and Application insights. These metrics will include gauges, histograms, and counters. Add ...

What is the best way to incorporate personalized events into an array using JavaScript?

Imagine we have an array called var arr = [1, 2, 3]. I am looking for a way to create a method that can observe any changes made to this array. The idea is something similar to the following: arr.on('change', function () { // perform some ac ...

Looking for a way to implement a vertical autoscroll <ul> list that responds to mouse movement using JavaScript and jQuery

Could you assist me in enabling the list items to be moved using mouse movement? When the user moves the mouse cursor vertically upward over the list, the list should scroll downward. If the user moves the mouse cursor downward over the list, the list shou ...

margin-top: automatic adjustment, with a minimum of 50 pixels

I am trying to add a minimum of 50px margin to the top of my footer tag using CSS, but I haven't been successful with the min() function. I'm not sure if I am overlooking something or if there is another correct approach to achieve this. * { ...

The Node.js express-generator application encounters a problem and is unable to start because of a TypeError: app.set function is not recognized

During the setup of my application using nodejs and express-generator, I encountered an issue when running the following commands in my terminal: npm install multer --save npm audit fix Afterwards, when I attempted to run node ./bin/www I received an err ...

Have developers created an event trigger for when google maps controls finish loading?

While I am aware of the tilesloaded event, it appears that the controls load after this event. My goal is to use jQuery to retrieve the controls, but I am struggling to identify the appropriate event to listen for. ...

React JavaScript application encountered an error: Uncaught SyntaxError due to an unexpected token '<'

My program encountered a syntax error at line <div>Hello World!</div> This is the code that is causing the error <!DOCTYPE html> <html> <head> <script src="libs/react.min.js"></script> <script src="lib ...

Problem with Node JS controller when using async/await

While working on my Node API controller, I encountered an issue with my 'error-handler' middleware related to using an asynchronous function. TypeError: fn is not a function at eval (webpack:///./app/middleware/errorHandler.js?:16:21) T ...

Retrieving JSON information from a PHP server

Currently, I am working on retrieving JSON data from a table that I am querying on my WAMP server using a select.php file. The data appears correctly in the browser, but strangely, Android is unable to download the data. The select.php file contains the f ...

What is the reason for Jquery AJAX appending additional path to the relative path?

I am encountering an issue with the following code snippet $.ajax({ url: "search/prefetch", success: function (data) { $(".result").html(data); alert("Load was performed."); }, dataType: "json" } ...

What is the best method for extracting specific JSON response elements and appending them to an array?

I've been utilizing the Nomics cryptocurrency API in my project. Below is an example of the Axios call: axios.get(apiURL + apiKey + apiSpecs) .then(function (response) { // sort data by highest market cap console.log(response.data) }) Here' ...

What could be causing the Uncaught Error to persist even after using .catch()?

Check out this code snippet: function pause(ms:number) { return new Promise((resolve:any,reject:any) => setTimeout(resolve,ms)) } async function throwError(): Promise<void> { await pause(2000) console.log("error throw") throw new ...

Encounter 404 errors when using MVC 5 Api controllers

Controller: public class DownloadListController : ApiController { private MovieService _movieService; public DownloadListController() { _movieService = new MovieService(); } public void Post([FromBody]string asd) { ...

Unexpected behavior occurs when ajax is added to an array for jQuery promise results

In my code, I have an each loop that makes individual AJAX requests and stores them in an array like this: var promises = []; $items.each(function(k, v) { promises.push( $.ajax({ url: ..., .... }) ); }); $.when.app ...