Retrieving JSON data from the controller with fullCalendar

I am struggling with implementing the fullCalendar library in Visual Studio 2015. I am encountering issues when trying to load events using an AJAX request. The events are not populating on the calendar as expected. If I provide only a single datetime and set allDay to true, the event shows up. However, I need it to work with specific times and have multiple events per day.

Here is my JS code:

$(document).ready(function () {

$(".calendar").fullCalendar
    ({
        header: {
            left: 'month,basicWeek,basicDay,today',
            center: 'title',
            right: 'prev,next'
        },
        weekends: false,
        eventLimit: true,
        theme: true,
        editable: false,
        fixedWeekCount: false,
        events: function(start, end, timezone, callback)
        {$.ajax
            ({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Calendar/GetCalendarEvents",
                dataType: 'json',
                success: function (data)
                {

                    var events = [];
                    $.each(data, function (index, value) {

                        events.push({
                            id: value['id'],
                            title: value['title'],
                            date: value['date']
                            //all data
                        });
                        console.log(value)
                    });
                    callback(events);
                },
                error: function (xhr, err) {
                    alert("ERROR! - readyState: " + xhr.readyState + "<br/>status: " + xhr.status + "<br/>responseText: " + xhr.responseText);
                }
            });

        }   });})

Note: This code represents one of several attempts I've made to resolve the issue.

Now moving onto the Controller code:

public ActionResult GetCalendarEvents()
    {
        var events = new List<VMCalendarEvents>();
        var db_events = db.PatientVisits.ToList();
        foreach(var e in db_events)
        {
            DateTime visit_start = Convert.ToDateTime(e.VisitStart);
            DateTime visit_end = Convert.ToDateTime(e.VisitEnd);

            var calEvent = new VMCalendarEvents
            {
                id = e.PatientVisitID.ToString(),
                title = "Placeholder Title" + e.PatientVisitID.ToString(),
                date = visit_start.ToShortDateString(),
                start = visit_start.ToString(),
                end = visit_end.ToString(),
                editable = true,
                allDay = false

            };
            events.Add(calEvent);
        }

        var rows = events.ToArray();
        return Json(rows, JsonRequestBehavior.AllowGet);}

View Controller Code Output

Preview JS Objects from Controller

UPDATE: Issue Resolved

After conducting some investigation, I decided to use Razor within MVC to tackle the problem. Instead of storing the logic in a separate JS file, I included it in a script section within the HTML file. By incorporating the following code snippet, I managed to receive objects in the desired date formats (yyyy-MM-ddTHH:dd & MM/dd/yyyy hh:mm tt):

    $(function () {

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        defaultDate: '2017-06-12',
        editable: true,
        events: '@Url.Action("GetCalendarEvents", "Calendar")',

    });

});

I utilized the URL Action command to call the Controller and obtain JSON data as an action result.

Answer №1

When working with Fullcalendar, be cautious of using slashes '/' in your date fields as it may cause issues. It is recommended to use hyphens '-' instead. For more detailed information on date/time formats, you can refer to the documentation available at https://fullcalendar.io/docs/utilities/Moment/.

If you need guidance on incorporating JSON data from AJAX into Fullcalendar, here is an example code snippet that I have used. Please note that in this example, the events do not include an end time:

{
    $.ajax({
        url: 'example.json',
        dataType: 'json',
        success: function(doc) {
            var events = [];
            $.each(doc, function(index, element) {
                events.push({
                    title: element.title,
                    start: element.time,
                    url: element.url
                });
            });
            callback(events);
        }
    }) //ajax
}

Take a look at the content of the JSON file (example.json) that I have referenced in the code above:

[
    {"time": "2017-06-06 09:00:00", "title": "Get It Done in June ", "url": "http://example.org"},
    {"time": "2017-06-07 14:00:00", "title": "Fighting Imposter Syndrome for Dissertating Students ", "url": "http://example.com"},
    {"time": "2017-06-14 14:00:00", "title": "Entering into the Academic Conversation", "url": "http://example.biz"}
]

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

Converting VB constants to C# language

In VB.Net, there are several constants like vbTab. Is there an equivalent in C#? ...

Tips for displaying ajax response in bootstrap modal

I am looking to create a modal that will display dynamic data retrieved from a query when a user clicks on a specific school. I have received the response, but I am struggling to figure out how to display it in the modal. Any suggestions? Button: <a h ...

What is the best way to create a table using a List in MVC?

I need to showcase a List containing Name, Item, and Group# in a table format. Is there a way to organize this data with names in the first row, items in the second row, and group numbers in the third row. Name: | Alice | Ben | Sarah | Noah | Item: | B ...

Use JavaScript or JQuery to insert an additional set of unordered list items

I have completed the coding for the initial HTML and JavaScript/JQuery components. Now, I am looking to enhance the final common list by wrapping it with an additional UL tag using JavaScript/JQuery. This means that the final common list will be enclosed b ...

Explore the functionality of the webix grid by clicking on the url column

I've recently created a table in Webix, and I have a column labeled "TBD" where I display a URL. My question is: how can I make this URL, 'https://pops.dra.com/TBD.php?jour=$adep&arc=$ads', clickable? while($row = mysqli_fetch_array($req ...

The dynamic URL parameters are altered by the Browser's back button

I am currently working on a website where the URL parameter is updated based on user actions. This update triggers changes in the webpage without the need for refreshing. An example scenario would be in an E-commerce site where the URL changes when the use ...

Utilizing AWS's getObject function to render an image directly in the web browser

I'm currently utilizing the @aws-sdk/client-s3 and attempting to access an image from a private bucket in AWS s3. Within my NextJS code, I have set up an API endpoint that is supposed to retrieve the image and then dynamically assign the src attribut ...

I'm experiencing issues with Visual Studio where I cannot launch any projects as the application keeps displaying the error message: "The application was unable to

Operating System: Windows 10 x64 Integrated Development Environment: Visual Studio 2012 x32 Frameworks: .NET Framework 3.5 and 4.6 I am facing issues with running/debugging/F5-ing projects in Visual Studio. I have attempted to work on various projects l ...

Prevent refreshing Google Maps when changing routes in AngularJS

Utilizing a Google map as the background for my website adds a unique visual element to the data displayed on different routes. However, I have encountered an issue where the map reloads with every route change, resulting in an unsightly flash of white tha ...

Obtaining a value from HTML and passing it to another component in Angular

I am facing an issue where I am trying to send a value from a web service to another component. The problem is that the value appears empty in the other component, even though I can see that the value is present when I use console.log() in the current comp ...

Using Angular to link Google Places API responses to a form: a guide on merging two different length objects with a shared key

I'm struggling with a key concept here regarding displaying the results of a places autocomplete query. I want to replace the types[0] name with more familiar terms such as suburb or city instead of sublocality_level_1 or administrative_area_level_1 ...

Get information for ListBox widget

I have successfully populated a list box with data. Now, I need to retrieve data based on a specific skill set in a gridview. For example, if a user selects "android" from a dropdown list and clicks a button, the gridview should display only the people w ...

Posting JSON data in Java for Android development

Hey there! I'm struggling to extract data from EditText and convert it into a JSON object. However, the JSON object returned is empty without any data. It only contains keys without being linked to the input values in EditText, as seen on the screen. ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

Error Encountered: Unexpected Identifier in Angular 7 External jQuery Plugin

Struggling to convert a jQuery template to Angular7, I'm facing an issue with loading .js files from the assets folder in the original template to make it functional. Upon starting the application with: ng serve, I encounter the following error in th ...

Execute CSS within jQuery code only when the body class is present

I am attempting to use CSS (display: none;) within a script to hide elements from my menu only if a specific language is active. When the body class changes from one language to another, I want the script to check if the body class of a certain language ...

Fade-in animation of a clock on an SVG image

I am trying to achieve a unique fade-in effect for an SVG image in my HTML. The challenge is to make the fade-in start from the top of the image and progress in a circular motion until it completes a full circle. An example of the effect I am aiming for is ...

What is the best way to transfer the value of a radio button, retrieved from a database, to a textbox?

Greetings, I am trying to figure out how to pass the value of a radio button to a textbox using jQuery and PHP. The radio buttons are generated dynamically based on rows from my database, so I set the row ID as the ID for each radio button. However, the co ...

Even after assigning the class "img-fluid" to my image, it still fails to properly adjust to the screen size

I added the class "img-fluid" to my image in Bootstrap, but it's not fitting on my webpage. What should I do? <img src="images\406201.jpg" class="img-fluid" alt="..."> <div style="margin-top: 0p ...

Utilize CannonJS to create a realistic floor where a ball can adhere to the surface

Newbie Inquiry: I'm attempting to drop a ball and have it stick to the floor or even roll over a plane. Currently, it's passing through the plane without any interaction. I'm unsure of where I may have gone wrong or if there's an error ...