In my specific scenario, what is the most effective method for retrieving data from an EntityFramework database using JavaScript?

Currently, within my ASP.NET MVC Core2 project, I have a model in the EF database that contains multiple properties:

public class SchoolEvents
    {
        public long ID { get; set; }
        [Required]
        [StringLength(40, ErrorMessage = "Max 40 characters")]
        public string Title { get; set; }
        [Required]
        public string Description { get; set; }
        [Required]
        public DateTime WhenHappens { get; set; }
    }

Retrieving data from the EF database using MVC Razor Views is not an issue for me. However, in one of my views, I am utilizing a JavaScript Calendar plugin to display events from the database on it. To achieve this, the script requires data in the following format:

{ title: 'EventTitle', description: 'Few words about the event', datetime: new Date(2018, 8, 14, 16) }

It appears that I need to use a 'for' loop in the script to iterate through the database objects.

Since I am still a novice in JS, currently the only method I am aware of involves:

- creating a JSON file in the controller:

[Route("events")]
        [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
        public ActionResult Comments()
        {
            var _events= _context.Events.OrderBy(c => c.ProductID).ToList(); //yes, I know, I should use repository in the best practice
            return Json(_events);
        }

- writing a function like 'loadEventsFromServer()' in the JS file, which utilizes XMLHttpRequest or Fetch and parses the data (still unsure about how to perform the parsing).

That's all I know. Do you have any alternative suggestions?

EDIT:

Including a section of the plugin code regarding the console error 'd is undefined' :

for (var i = 0; i < 42; i++) {
                var cDay = $('<div/>');
                if (i < dWeekDayOfMonthStart) {
                    cDay.addClass('c-day-previous-month c-pad-top');
                    cDay.html(dLastDayOfPreviousMonth++);
                } else if (day <= dLastDayOfMonth) {
                    cDay.addClass('c-day c-pad-top');
                    if (day == dDay && adMonth == dMonth && adYear == dYear) {
                        cDay.addClass('c-today');
                    }
                    for (var j = 0; j < settings.events.length; j++) {
                        var d = settings.events[j].datetime;
                        if (d.getDate() == day && d.getMonth() == dMonth && d.getFullYear() == dYear) {
                            cDay.addClass('c-event').attr('data-event-day', d.getDate());
                            cDay.on('mouseover', mouseOverEvent).on('mouseleave', mouseLeaveEvent);
                        }
                    }
                    cDay.html(day++);
                } else {
                    cDay.addClass('c-day-next-month c-pad-top');
                    cDay.html(dayOfNextMonth++);
                }
                cBody.append(cDay);
            }

Answer №1

My recommendation would be to utilize an ajax request for this task.

Javascript : Ajax

        $.ajax({
            type: 'POST',
            url: '@URL.Action("Comments","Controller")',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: {},
            success: function (data) {
             var events = new Object();
                events = $.map(data.d, function (item, i) {
                    for (var j = 0; j < data.d.length; j++) {
                        var event = new Object();                            
                        var startDate = Date.parse(item.WhenHappens )
                        event.start = startDate;                           
                        event.title = item.Title;
                        event.backgroundColor = "#c6458c";
                        event.description = item.Description;
                        return event;
                    }
                })
                callCalender(events);
            },
            error:function(e){  

            }
        });

Controller

[Route("events")]
    [HttpPost]
    [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
    public ActionResult Comments()
    {
        var _events= _context.Events.OrderBy(c => c.ProductID).ToList(); //yes, I know, I should use repository in the best practice
        return Json(_events);
    }

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

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

Can one extract a property from an object and assign it to a property on the constructor?

Currently working with TypeScript, I am looking to destructure properties from an object. The challenge lies in the fact that I need to assign it to a property on the constructor of the class: var someData = [{title: 'some title', desc: 'so ...

Remove the image by clicking on the "X" icon located on the top right corner of the image

One of my tasks involves deleting an image by clicking on the "X" mark located at the top right corner of the image. To achieve this, I referred to this CSS fiddle http://jsfiddle.net/yHNEv/. Sample HTML code: <div class="img-wrap"> <span ng-c ...

The IP validation feature in the textbox is not performing as anticipated

My goal is to have a textbox that receives an IP address and validates it before submission. To achieve this, I've developed a JavaScript class called `validityCheck`. In my main Vue.js component, I aim to utilize this class to validate the input&apo ...

What could be causing the value of response.name to be undefined in this situation?

Despite extensively searching through various StackOverflow threads, none of the suggested solutions seemed to work for my specific scenario. Upon analyzing the response using console.log(response), I received an "Object Object" message. I am puzzled as to ...

Hinting the type for the puppeteer page

I am trying to type hint a page variable as a function parameter, but I encountered a compilation error. sync function than_func(page:Page) ^ SyntaxError: Unexpected token: ...

Installing material-ui using npm does not always result in getting the most up-to-date version

I'm currently facing a dilemma with an abandoned project that serves as the admin tool for my current project. The Material-UI version used in this project is 0.19.4. However, when I remove the dependency from my package.json file and execute npm inst ...

Error Loading JQuery: The function $() is not recognized in the Shopify platform

I seem to be overlooking something obvious. I am using Shopify and have included jQuery in the head section of the theme.liquid file: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> This script is placed rig ...

VueJS, when used in conjunction with Vuetify, might require an extra loader to handle scoped css

While attempting to compile my VueJS code using webpack, I encountered an error with the following code: <template> <v-app-bar app color="blue" flat height="100px"> <v-img class="mx-2" contain max-height="80" m ...

When the Jqueryui dialog is closed, it effectively terminates the current JavaScript thread

Hello there, I'm currently facing an issue with closing my jQuery dialog box. The situation involves a comet connection that sends messages to my browser. My goal is to perform certain actions upon receiving a message, close the dialog, and then conti ...

The C# HttpWebResponse returns a response that is encoded

Recently, I encountered a situation where I had to send an HttpWebRequest to a server. The response that I received was in JSON format but encoded in a way that made it difficult to read: �\b\0\0\0\0\0\0��A� @ѻ ...

What could be causing my JavaScript source to fail to load in an HTML document?

Currently, I am in the process of creating a basic offline dinosaur game using HTML, JS, and CSS that is well-known to everyone. I have been diligently working on it and have successfully made everything function for a few hours. However, out of nowhere, m ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

Retrieve a value from a JSON string when the parent object's name is not predetermined

I am facing a challenge with extracting the property value named "Mode" from a JSON string, without knowing the parent property name. Here is an example of the JSON structure: { "CommomData": { "DateTime": { "Year": 2019, "Month": 3, ...

Using Parseint in a Vue.js method

For instance, let's say this.last is 5 and this.current is 60. I want the sum of this.last + this.current to be 65, not 605. I attempted using parseInt(this.last + this.current) but it did not work as expected. <button class="plus" @click="plus"&g ...

Creating visualizations by overlaying shapes onto images using specified coordinates in jQuery

I have a web application in development that integrates with the skybiometry API. Their demo showcases a fantastic user feedback system displayed after facial recognition, similar to the one shown below. I am currently working on implementing a similar fe ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

Execute a post request upon clicking with NEXT JS, while also firing off a get request

I'm facing an issue where I need to post and get my data when clicking on the same button (similar to writing and displaying comments). However, whenever I click the button, everything seems to be working fine but a request with a 304 status code star ...

Tips for adjusting column sizes in react-mui's DataGrid based on screen size

I would like the title column to occupy 3/4 of the full row width and the amount column to take up 1/4 of the full row width on all screens sizes (md, sx...). Here is the updated code snippet: import React from 'react' const MyComponent = () =&g ...

A collapsible select list with checkboxes for children items

I am currently developing a website using Vue.js, HTML, and SCSS. I am looking to implement a drop-down functionality similar to the animated example provided in the gif below: https://i.stack.imgur.com/Mia2D.gif The gif demonstrates how the drop-down me ...