When the page is loaded, populate FullCalendar with events from the model

On page load, I am attempting to populate events with different colors (red, yellow, green) on each day of the calendar. Here is a simple example showcasing events for three days:

https://i.sstatic.net/YzJ4E.png

I have data in a model that indicates the available amount of free pallets for orders on specific dates. If there are less than 10 free pallets, the event should display as red; if it's between 10 and 149, then it should be yellow, and so on (as illustrated in the example).

This is the current script for "FullCalendar":

<script type="text/javascript">
    var calendar = new FullCalendar.Calendar($("#calendar")[0], {
        plugins: ['interaction', 'dayGrid'],
        height: 'auto',
        defaultView: 'dayGridMonth',
        weekNumberCalculation: 'ISO',
        weekNumbers: true,
        events: [
            {
            title: '150-300',
                start: '2020-07-16',
            color: 'green'
            },
            {
            title: '10-149',
                start: '2020-07-15',
            color: 'yellow'
            },
            {
            title: '<10',
                start: '2020-07-14',
            color: 'red'
            }],
        dateClick: function (info) {
            window.location.href = "Incoming?date=" + info.dateStr;
        }
    });
    calendar.render();
    calendar.select('@(Model.Date?.ToString("yyyy-MM-dd"))');
</script>

The pre-defined events provided above are simply examples.

My goal is to dynamically generate colored events on every date within a month when the page loads, based on the data from the model in my MVC (.Net) application. How can I achieve this?

I have attempted various solutions suggested in this forum for dynamically adding events, but they either don't work or involve unnecessary post actions, which I believe are not needed in this case.

UPDATE

I have tried creating a JsonResult action in my controller, generating a valid Json string that I can feed to FullCalendar. Unfortunately, it does not seem to be working. Here is the action:

public JsonResult GetCalendarEvents(string id, DateTime? date)
        {
         //Database related code to get dates and their amount of free pallets (this is where I use the id and date parameters)
                var idEvent = 1;
                foreach (var v in days)
                {
                    var title = "";
                    var color = "";
                    var freecap = (v.DayOfWeek == DayOfWeek.Friday ? 200 : 300) - model.Incomings.Where(x => x.ExpectedDate == v &&
                            x.ExpectedPallets.HasValue).Sum(x => x.ExpectedPallets);


                    if(freecap >= 150)
                    {
                        title = "150-300";
                        color = "green";
                    } else if(freecap < 150 && freecap >= 10)
                    {
                        title = "10-149";
                        color = "yellow";
                    } else
                    {
                        title = "<10";
                        color = "red";
                    }

                    events.Add(new CalendarEvent { id = idEvent, title = title, allDay = "", start = v.Date.ToString().Substring(0,10), end = v.Date.ToString().Substring(0, 10), color = color });
                    
                    idEvent++;
                }
            }

            return Json(events, JsonRequestBehavior.AllowGet);

The generated Json result appears like this:

[{"id":1,"title":"150-300","allDay":"","start":"19-07-2019","end":"19-07-2019","color":"green"},{"id":2,"title":"150-300","allDay":"","start":"22-08-2019","end":"22-08-2019","color":"green"},{"id":3,"title":"150-300","allDay":"","start":"30-08-2019","end":"30-08-2019","color":"green"}]

The attributes id, allDay, and end were added following the advice from a top answer on this post: Jquery Full Calendar json event source syntax, but unfortunately, that didn't solve the issue.

Despite these efforts, none of the events appear on the calendar, yet the page and calendar load without any issues (without events displayed). What could I be overlooking here?

Answer №1

Thanks to the assistance from user @ADyson, I was able to find a resolution for my challenges. Below is an example and explanation that might be helpful for others encountering similar issues or working with FullCalendar events using JSON in an MVC setting.

To start off, I have created an event class containing necessary attributes (although I primarily utilize title, start, and color attributes, including the rest as they might be needed, based on this post Jquery Full Calendar json event source syntax):

public class CalendarEvent
    {
        public int id { get; set; }
        public string title { get; set; }
        public string allDay { get; set; }
        public string start { get; set; }
        public string end { get; set; }
        public string color { get; set; }
    }

In the controller, I have the action GetCalendarEvents structured like this:

public JsonResult GetCalendarEvents(string id, DateTime? date)
        {
         //Database related code to retrieve dates and their respective available pallet quantities (utilizing the id and date parameters)
                var idEvent = 1;
                foreach (var v in days)
                {
                    var title = "";
                    var color = "";
                    var freecap = (v.DayOfWeek == DayOfWeek.Friday ? 200 : 300) - model.Incomings.Where(x => x.ExpectedDate == v &&
                            x.ExpectedPallets.HasValue).Sum(x => x.ExpectedPallets);


                    if(freecap >= 150)
                    {
                        title = "150-300";
                        color = "green";
                    } else if(freecap < 150 && freecap >= 10)
                    {
                        title = "10-149";
                        color = "yellow";
                    } else
                    {
                        title = "<10";
                        color = "red";
                    }

                    events.Add(new CalendarEvent { id = idEvent, title = title, allDay = "", start = v.Date.ToString().Substring(0,10), end = v.Date.ToString().Substring(0, 10), color = color });
                    
                    idEvent++;
                }
            }

            return Json(events, JsonRequestBehavior.AllowGet);
}

The primary function of the action involves fetching pertinent data from our database and determining the appropriate color and name for each event. This determination is based on the quantity of free pallets available at our warehouse on a specific date. This method can be adjusted based on individual requirements, but essentially, it compiles a list of events to be returned as a Json result.

In the View where the FullCalendar script and widget are located, I reference the events to the action using the following snippet (be sure to modify the route, controller, action, and id string according to your setup):

events: '@Url.HttpRouteUrl("Default", new { controller = "Home", action = "GetCalendarEvents", id = "DOD" })'

If you notice a "12a" prefixing the title of all events, it indicates the start time of the event (which has not been set). To remove it, you can include the following lines in the script:

timeFormat: 'H(:mm)', // uppercase H for 24-hour clock
displayEventTime: false

This is how my complete FullCalendar script looks:

<script type="text/javascript">
    var calendar = new FullCalendar.Calendar($("#calendar")[0], {
        plugins: ['interaction', 'dayGrid'],
        height: 'auto',
        defaultView: 'dayGridMonth',
        weekNumberCalculation: 'ISO',
        weekNumbers: true,
        events: '@Url.HttpRouteUrl("Default", new { controller = "Home", action = "GetCalendarEvents", id = "DOD" })',
        timeFormat: 'H(:mm)', // uppercase H for 24-hour clock
        displayEventTime: false,
        dateClick: function (info) {
                window.location.href = "Incoming?date=" + info.dateStr;
            }
        });
    calendar.render();
    calendar.select('@(Model.Date?.ToString("yyyy-MM-dd"))');
</script>

The resulting JSON output should resemble the following format:

[{"id":1,"title":"150-300","allDay":"","start":"2019-07-19","end":"2019-07-19","color":"green"},{"id":2,"title":"150-300","allDay":"","start":"2019-08-22","end":"2019-08-22","color":"green"},{"id":3,"title":"150-300","allDay":"","start":"2019-08-30","end":"2019-08-30","color":"green"}]

It's crucial to follow the date format yyyy-MM-dd, as emphasized by @ADyson. In case further details are required, refer to the FullCalendar documentation linked by @ADyson: Event Parsing and Events (as a json feed)

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

The initial $http POST in Angular ends up hitting the error path within the .then function despite the successful execution of the

Something strange is happening to me. This peculiar behavior occurs only on the initial POST request. However, when I resubmit the form, the subsequent requests work perfectly fine. The first $http post call leads to the error function in .then, even thou ...

How to retrieve data from a nested object in Angular templates

I am working with a "post" object that has an "author" property, linking each post to the author who created it. The "author" property is a nested "user" object with a "name" property. My goal is to access the "name" of the user associated with a specifi ...

When using JSX, it's important to wrap adjacent elements within an enclosing tag to avoid errors. Make sure to properly wrap the JSX tags to

import React, { useState } from 'react'; import ReactDOM from 'react-dom'; function DisplayData(props) { //creating the DataList const dataList = data.map(data => ( <><span>{data.name}</span> nbsp; <span> ...

Automatically display comma-separated values from a MySQL column as checked options inside Bootstrap-Select with Bootstrap-Select

Currently, I am using Bootstrap-Select for a project and I want to have certain options in a multiple dropdown list checked based on values from a MySQL column separated by commas. While looking for a solution, I came across a similar question but couldn&a ...

Using Javascript and jQuery to validate strings within an array

My existing jQuery code works perfectly by returning true if it matches the specified name. jQuery(function($) { var strings = $(".user-nicename").text(); if (strings === "name1") { $('.mention-name').hide(); $('.se ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

Trouble with $http response not appearing in AngularJS application

Currently, I am in the process of developing an angularjs application and encountering a challenging issue with setting up the $http connection to a php file. The header is displaying a response that I echoed from php. Nevertheless, two key problems persis ...

I could use some assistance in creating arrays from a JSON file that contain identical keys

Here's the data in JSON format: [ { "id": 1, "picture": "image-hero-paramour.jpg", "title": "Project Paramour", "subheading": "Project made for an art museum near Southwest London. Project Paramour is a stateme ...

Generating Vuetify badges and icons with createElement in the render function: A step-by-step guide

Within my Vue application, I utilize a v-data-table. The column values are generated using a render function within a functional component as illustrated below: render(createElement) { if (this.$props.format) { return this.$props.format(this.ite ...

Managing errors in Node.js when inserting data into MongoDB

Hello everyone, I'm currently working on handling errors in the user signup module using Express. However, I'm facing an issue where the errors are not being handled correctly. Here is my code: handler.post(async (req, res) => { let otp = M ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

Post response not being received by Node.js Express static file on the client side

Greetings all, I'm currently delving into mobile development and seeking to expand my knowledge of the Node.js runtime. As part of my learning process, I have a simple client-side "app" written in JavaScript that I am attempting to integrate with a No ...

Why is it necessary to omit node_modules from webpack configuration?

Check out this webpack configuration file: module.exports = { mode: "development", entry: "./src/index.ts", output: { filename: "bundle.js" }, resolve: { extensions: [".ts"] }, module: { rules: [ { test: /\.ts/ ...

displaying JSON information in a datatable

I recently integrated the jquery datatable plugin into my project. My goal is to display JSON data within this datatable. Object {Titillium-Light: "data1", Custom font: "data2", Titillium-Bold: "data3", Titillium-LightUpright: "data4"} My objective is to ...

Find Discounts Array

Is there a way to determine the Array of Discounts based on the Base Price initially and then calculate them against the Amount After Discount? In the image provided below, we have the Base Price. This base price may include multiple discounts. Each disc ...

Proper Structure for Node System (BASIC)

Overview Recently, I entered the world of Node.js and built some basic back end functionality. However, I realized that everything was clustered in one file (index.js) which led me to explore tutorials on using express router middleware and adapting a mod ...

What is the purpose of making a "deep copy" when adding this HTML content?

My canvas-like element is constantly changing its contents. I am attempting to execute a function on each change that captures the current content and adds it to another element, creating a history of all changes. window.updateHistory = func ...

I am unable to organize an array

I stumbled upon a discussion about clearing an array in JavaScript, but unfortunately I can't participate there. So, here's my query: I have the following code snippet: sumarray.length=0; sumarray = []; for (var i=0; i<3; i++) sumar ...

Encountered an error with symbol '@' while utilizing ES6 decorators

I have recently set up a React project and now I'm attempting to integrate MobX into it. This requires using decorators such as: @observable However, when I try to implement this, I encounter the following error: https://github.com/mobxjs/mobx Mod ...

Instructions for creating a histogram using predetermined bin values

After searching, I noticed that most tutorials on creating histograms with matplotlib focus on plotting histograms for unbinned data using the hist function. How can I go about drawing a histogram from pre-binned data? To provide more context, here is the ...