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:

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

React JS - Breaking down the distinction between PublicTheme and PublicTheme

In my React project, I am currently working on creating the admin dashboard and designing the UI area for user interaction. I have encountered an issue where I am unable to separate the admin theme from the PublicTheme. Even when navigating to "/admin/lo ...

Implementing user profile picture display in express.js: A step-by-step guide

I'm having trouble displaying the profile picture uploaded by users or employees in my application. Although the picture uploads successfully, it doesn't show up and gives an error when I try to redirect to the page. Cannot read property &ap ...

Ways to alter the typography style if the text exceeds a certain length

I need some assistance with using Material UI in my ReactJs project with TypeScript. I am trying to decrease the font size of typography when the text exceeds 3 lines. Here is a snippet of my code: const checkFontSize =() => { if(text.leng ...

Using jQuery and AJAX manipulates the value of my variable

My AJAX request seems to be causing jQuery to change the variable that is passed to it. Here is the JavaScript code: <script type="text/javascript"> function ResolveName(id) { $.ajax({ url : 'resolvename.php', ...

Using Javascript, when the command key is pressed, open the link in a new window

Currently, I am working on a Javascript function that opens links in a new tab only when the "command" key is pressed on an Apple computer. Here is what I have so far: $(document).on('click','a[data-id]',function(e){ if(e.ctrlKey|| ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...

Enhance the numerical worth of the variable through the implementation of the function

I'm working on a JavaScript timer but I'm struggling with assigning the value of a parameter to a global variable. Currently, I can achieve this without using parameters, but I really want to streamline my code and reduce the number of lines. He ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

How can I determine when a WebSocket connection is closed after a user exits the browser?

Incorporating HTML5 websocket and nodejs in my project has allowed me to develop a basic chat function. Thus far, everything is functioning as expected. However, I am faced with the challenge of determining how to identify if connected users have lost th ...

Using Jquery to make a Json request and incorporating a callback function to populate an

I have successfully implemented a cascading drop down feature in my form. However, I am facing issues with the callback function not functioning properly after submitting the form. I am unsure what is causing this problem. Despite making suggested changes ...

Tips for creating Firestore rules for a one-on-one messaging application

After creating a one to one chat app for a website using Firebase and Firestore, I am now looking to set up the Firebase Firestore rules for the same. The functionality of the app involves checking if the user is [email protected], then retrieving chatids ...

Please display the Bootstrap Modal first before continuing

Currently, I'm facing a challenge with my JS code as it seems to continue running before displaying my Bootstrap Modal. On this website, users are required to input information and upon pressing the Save button, a function called "passTimeToSpring()" ...

The variable fails to receive a value due to an issue with AJAX functionality

I am struggling to figure out what's causing an issue with my code. I need to store the result of an AJAX request in a variable, specifically an image URL that I want to preload. $.ajax({ type: "POST", url: 'code/submit/submi ...

JavaScript and jQuery experiencing difficulty rendering proper style and image in output display

I am currently working on code that extracts information from a JSON variable and displays it on a map. The code looks like this: marker.info_window_content = place.image + '<br/>' +"<h4>" + place.name + "</h4> ...

Determine whether the color is a string ('white' === color? // true, 'bright white gold' === color? // false)

I am facing an issue with multiple color strings retrieved from the database. Each color string needs to be converted to lowercase and then passed as inline styles: const colorPickerItem = color => ( <View style={{backgroundColor: color.toLowerC ...

The parent component is failing to pass the form values to the child form group in CVA

My Angular application (view source code on Stackblitz) is running Angular 15, and it utilizes reactive forms along with a ControlValueAccessor pattern to construct a parent form containing child form groups. However, I am encountering an issue where the d ...

When the progress bar is clicked, the background color changes and then changes back again

https://www.w3schools.com/code/tryit.asp?filename=FG1ZE0NJ4ZX7 https://i.stack.imgur.com/Bnd0k.png I have created a progress bar that resembles the screenshot provided. When I hover over it, the color changes to green. However, I am looking for assistanc ...

Having trouble changing my array state in react?

I'm having trouble understanding why my React state isn't updating with the following code: state = { popUpMessages:[] } popUpMessage(id,name) { console.log("id ",id,"name ",name) const addUserObject = { id, name }; const new ...

Angular2 Window Opener

Trying to establish communication between a child window and parent window in Angular 2, but I'm stuck on how to utilize window.opener for passing a parameter to Angular 2. In my previous experience with Angular 1.5, I referenced something similar he ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...