JavaScript - An Efficient Method to Retrieve Data Imported from the Controller via Ajax

I am a beginner and I'm having trouble getting a list of objects called "Event" (OrderId, Date) from the MVC controller to JavaScript in the view. When I try to display the list as strings, it shows me "undefined". On the controller side, everything seems to be correct! I have been searching for my error but I can't find it. I have tried using # and without, also tried using foreach loop but I think something else might be wrong. Thank you for helping me!

The Controller :

[System.Web.Mvc.HttpGet]
public JsonResult getListEvent() {
   IList<Event> ListEvent = new List<Event>();
   ListEvent = DeserializeElement();
   return Json(new { ListEvent = ListEvent }, JsonRequestBehavior.AllowGet);
}

private List<Event> DeserializeElement () {
        List<Event> lt = new List<Event>();
    document.Load("eventXml.xml");
    foreach (XmlNode item in document.DocumentElement.ChildNodes) {
        Event e = new Event();
        e.OrderId = int.Parse(item.Attributes[0].Value);
        e.Date = Convert.ToDateTime(item.Attributes[1].Value);
        lt.Add(e);
    }
    return lt;
}

and the View :

function GetListEvent() {
    debugger;
    $.ajax({
        type: "GET",
        url: "Home/getListEvent",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            debugger;
            alert( data[0].OrderId);
            alert('#'+ data[1].Date);
            for (var item in data ) {
                alert('#' + data[item]);
            }
        },
        error: function (response) {
            debugger;
            alert('error');
        }
    });
}

Answer №1

I greatly appreciate your input, but upon further investigation, I have found that the item in question is actually located within another object.

Therefore, my code should be:

alert(data.ListEvent[0].OrderId);

instead of

alert(data[0].OrderId);

And it is important to note that "#" is not required in this instance;

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 PHP to fail in receiving data from AJAX requests?

Having an issue with a contact form on my live website. The form includes a button that triggers a function when clicked, onClick = 'send()'. The email is sent successfully with all its contents when testing on localhost with WAMP, but on the liv ...

splitting the array elements in JavaScript

I'm having trouble with my code that is supposed to separate the array in customer and customerportals. let j = 0; let k = 0; let myVar = []; $.each(Object.customer, function(index, value) { $.each(value.portal.customerPortal, function(innerIn ...

Interactive calendar feature displaying events upon hovering over a date

I need some assistance with displaying a drop-down list on full calendar events when hovering over the events. Can someone provide guidance? Here is a glimpse of what I currently have: https://i.sstatic.net/fZXMH.png I've attempted setting the z-in ...

"How to automatically populate an input field with a value when the page loads in an

I need assistance with setting the input value to 1 when the page is loaded, but for some reason, it remains empty. Can someone help me troubleshoot this issue? <tr *ngFor="let item of cartItems; let i=index"> <td class="cart_pr ...

What is the most effective method to guarantee the creation of an object prior to navigating through the code that relies on it?

I recently encountered an issue with my code that utilizes fetch() to retrieve and convert .tiff images into an html5 canvas for display in a browser using tiff.js (https://github.com/seikichi/tiff.js/tree/master). While the functionality mostly works as i ...

Experiment with try and catch while making a jQuery ajax call

I'm currently working on developing a Google Chrome extension that involves making an ajax request, similar to the GMail Checker extension. The issue I'm facing is that when I make a request using jquery and input incorrect credentials, it fails ...

AngularJS testing typically involves the use of the inject module injection process

Currently, I am working on testing a service called documentViewer, which relies on another service named authService. angular .module('someModule') .service('documentViewer', DocumentViewer); /* @ngInject */ function Do ...

Is Chrome launching a list of links in separate windows instead of tabs?

As I create a customized start page for myself, I've encountered a challenge. I want to include a link above all sections that, when clicked, will open all pages in a new tab. However, I'm facing an issue where only the first link opens in a new ...

Is there a way to verify if all the values in an array of objects are identical?

In this scenario, my array consists of entries with identical address IDs but different phone types and numbers. I am in need of assistance with iterating through the array to extract the phone type and number when the address ID matches. I seem to encount ...

Is there a way for me to fetch the post variables sent through $http.post in Angular within my Node.js backend?

My front end code looks like this. auth var time = 5; $http.post('/tasks/addTime', null, { headers: { Authorization: "Bearer " + auth.getToken() }, data: { id: "Me", time: time, } }); This is the back e ...

Display the data returned from a computed property PromiseResult using VueJS

After calculating the property shown below, it will output res, which is a Promise object. The reason I cannot place this script inside the created() or mounted() hook is due to the fact that this.selectedObject is null at that time. I am satisfied with t ...

Vuejs failing to update data

Let me begin by describing my scenario. I have a fee_map attribute in my data, which is a list of objects containing information about the fees students have to pay, their balances, payment methods, etc. Additionally, there is a computed property called &a ...

Encountering issues with rendering in React JS when utilizing state variables

I've been attempting to display content using the render method in React JS, but for some reason, the onClick code isn't executing. I'm currently enrolled in a course on Udemy that covers this topic. import React, { Component } from 'r ...

Develop a monitor for an entity that has not been created

Currently, I am tackling a feature that involves tracking an asynchronous request within a synchronous one. Let me elaborate. The code snippet I am working with looks something like this: const myObj = {}; function sendMessage(requestId, data) { kafkaP ...

Utilize paperclip and angularjs to easily upload files

I am currently working on integrating Angularjs upload functionality into my rails application: Angular File upload Below is my controller code for managing photos: def create @photo = current_user.photos.new(photo_params) respond_to do |format| if @ ...

Alteration of div background hue triggered by drop-down menu selection

Although I am more focused on creating UI designs, I decided to take up some short courses to brush up on my JavaScript skills. However, I encountered a problem where I needed to create a dropdown menu with four color options: red, blue, green, and yellow. ...

clicking on a DIV element

I am trying to trigger a JavaScript function by clicking on a DIV element, but for some reason it is not working as expected. I have gone through various examples provided by the helpful people here, but still can't figure out what I'm doing wron ...

Display the printed outcome in a fresh window

HTML: <form id="dbview" method="post" action="core/process.php"> .... <p style='text-align:center;'> <input id='delete' type='submit' name='process' value='Delete selected'/> < ...

Unable to display content on the ejs file

Currently, I have been diving into the world of node.js and exploring how to manipulate data by writing and reading from JSON files. It has been an interesting journey so far; however, I encountered a hiccup. Specifically, when attempting to post new data ...

Vue looping through nested checkbox groups

Here is an object I am working with: rightGroups: [ { name: "Admin Rights", id: 1, rights: [ { caption: 'Manage Rights', name: 'reports', ...