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

How can you prevent the browser from prompting to save your email and password when filling out a sign-up form?

I'm currently developing a PHP sign up form, but whenever I click on the sign up button, the browser prompts me to save the email and password. Is there a way to prevent this from happening? ...

Notify the user with a Jqgrid alert when they attempt to select multiple checkboxes

When editing rows, I wanted to avoid multiple selections. In order to achieve this, I need to check the condition if(count>1) and display an alert message. I am struggling to figure out how to retrieve the count of selected checkboxes in jqGrid. var m ...

Utilizing Nuxt3's auto-import feature alongside Eslint

I'm having trouble finding an eslint setup that is compatible with Nuxt3's auto-import feature to prevent no-undef errors. I have tried various packages like @antfu/eslint-config, plugin:nuxt/recommended, @nuxt/eslint-config, @nuxtjs/eslint-confi ...

Exploring the world of jQuery animation and background colors with Animate()

I'm currently attempting to implement a basic pulse effect by utilizing JQuery to modify the background color. However, I am facing issues with animating the backgroundColor property. function show_user(dnid) { /* dnid represents the HTML ID of a ...

The function Router.use() needs a middleware function, but instead, it received an undefined

Attempting to create an authentication app using Node.js, but encountering an error as described in the title. The code for app.js is already set up like this: var createError = require('http-errors'); var express = require('express'); ...

The issue of asynchronous behavior causing malfunctioning of the PayPal button

import { PayPalButton } from 'react-paypal-button-v2' <PayPalButton amount={total} onSuccess={tranSuccess} /> const tranSuccess = async(payment) => { c ...

The updates made to a variable within an ajax request are not immediately reflected after the request has been completed

My global variable is not displaying the expected result: function checkLiveRdv(salle, jour, dateus, heure) { var resu; var urlaction = myUrl; $.ajax({ type: "POST", dataType: "json", url: urlaction, data: myDatas, suc ...

Paste the formatted text from clipboard into the body of a react mailto link

I have a requirement for users to easily send a table via email by copying and pasting it into the subject line. You can view a live demo of this feature on CodeSandbox: copy and paste rich text Below is the function that allows users to copy and paste ri ...

What is the best way to eliminate the space between two columns of a row in Bootstrap 5 grid system?

In my quest to achieve the grid layout illustrated in the image below https://i.sstatic.net/4hsjw.jpg .col_1{ background-color: bisque !important; height: 500px; } .col_2 { width: 300px; height: 287px; background-position: cent ...

Delay reading body until npm request completes

My current challenge involves using npm request and cheerio to extract webpages and analyze their HTML structure. Everything works smoothly in scenarios where the HTML is available upon request. However, I am facing a problem when a website initially displ ...

Instructions on utilizing Tesseract.recognize in Node.js

I am working on developing an OCR program but encountered some issues while declaring the 'Tesseract.recognize' method. Here is the code snippet: const express = require('express'); const fs= require('fs'); const multer = r ...

Reactjs encountering issues loading css file

Currently, I am working on a project in Reactjs with Nextjs. To add CSS to my project, I have stored my CSS files in the 'styles' folder. In order to include them, I created a file called '_document.js' and implemented the following cod ...

What are the steps to connect to multiple databases with ExpressJS?

I have a server with 3 databases containing identical tables. The databases are named DB1, DB2, and DB3. When working with a specific database, I utilize the following code in app.js: var cnxDB = require('./routes/cnxDB'); app.post('/user ...

Guide on sending a JSON object to an EJS javascript loop efficiently

Seeking assistance with passing a Json object named myVar to the home.ejs file below. How should I assign the value to the variable called data? <table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%"> ...

Ways to update a ViewComponent using Ajax in Asp.net Core 3.1

How can I make FavoriteComponent refresh when the "a" tag is clicked? Html : <div id="favorite-user"> @await Component.InvokeAsync("FavoriteComponent") </div> Action Html : <a id="add-fav" onclick="addfavorite('@pr ...

Conceal the menu when tapping anywhere else

I am working on a project that involves implementing HTML menus that can be shown or hidden when the user interacts with them. Specifically, I want these menus to hide not only when the user clicks on the header again but also when they click outside of th ...

Ways to modify client socket from JavaScript to PHP

Looking for a way to convert a client socket from JavaScript to PHP in order to receive data from the server socket? Check out the PHP socket Bloatless library here. This is an example of the Client Javascript code: <script> // connect to chat appl ...

What sets cross-fetch apart from isomorphic-fetch?

According to the Redux documentation, cross-fetch is the preferred choice, whereas most other sources recommend using isomorphic-fetch. What sets these two apart? ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

Accessing information from a database using SQL commands in C# programming

I'm working on creating a book management system using C#. The data for the books is stored in a database with the extension .ACCDB. My first task is to retrieve the bookIDs associated with a specific series by executing the following SQL query: sql ...