Display contents of SQL Table with Asp.Net Core MVC and FullCalendar

438 Views Asked by At

I have setup my app to display events on calendar. However, whilst the correct number of events will display the date and time is always the current date and time rather than what I have input into the SQL db table. Any help with what I am doing wrong would be greatly appreciated. My code is below:

View

@model IEnumerable<wccFacilityBookings.Models.Events>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div id="calender"></div>

<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title"><span id="eventTitle"></span></h4>
            </div>
            <div class="modal-body">
                <p id="pDetails"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.css" rel="stylesheet" media="print" />

@section Scripts{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>

    <script>
        $(document).ready(function () {
            var events = [];
            $.ajax({
                type: "GET",
                url: "/applications/GetEvents",
                success: function (data) {
                    $.each(data, function (i, v) {
                        events.push({
                            title: v.Subject,
                            description: v.Description,
                            start: moment(v.Start),
                            end: v.End != null ? moment(v.End) : null,
                            color: v.ThemeColor,
                            allDay : v.IsFullDay
                        });
                    })

                    GenerateCalender(events);
                },
                error: function (error) {
                    alert('failed');
                }
            })

            function GenerateCalender(events) {
                $('#calender').fullCalendar('destroy');
                $('#calender').fullCalendar({
                    contentHeight: 400,
                    defaultDate: new Date(),
                    timeFormat: 'h(:mm)a',
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,basicWeek,basicDay,agenda'
                    },
                    eventLimit: true,
                    eventColor: '#378006',
                    events: events,
                    eventClick: function (calEvent, jsEvent, view) {
                        $('#myModal #eventTitle').text(calEvent.title);
                        var $description = $('<div/>');
                        $description.append($('<p/>').html('<b>Start:</b>' + calEvent.start.format("DD- 
                        MMM-YYYY HH:mm a")));
                        if (calEvent.end != null) {
                            $description.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD- 
                         MMM-YYYY HH:mm a")));
                        }
                        $description.append($('<p/>').html('<b>Description:</b>' + 
                         calEvent.description));
                        $('#myModal #pDetails').empty().html($description);

                        $('#myModal').modal();
                    }
                })
            }
        })
    </script>
}

Controller

// GET: Applications/CalendarView
public IActionResult CalendarView()
{
    return View();
}

public JsonResult GetEvents()
{
    using (WCCFacilityBookingsContext context = new WCCFacilityBookingsContext())
    {
        var events =_context.Events.ToList();
        return Json(events);
    }
}

using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace wccFacilityBookings.Models
{
    public class Events
    {
        [Key]
        public int EventID { get; set; }
        public string Subject { get; set; }
        public string Description { get; set; }
        public System.DateTime Start { get; set; }
        public Nullable<System.DateTime> End { get; set; }
        public string ThemeColor { get; set; }
        public bool IsFullDay { get; set; }

    }
}

enter image description here

enter image description here

2

There are 2 best solutions below

1
On BEST ANSWER

Does this have something to do with it being Asp.Net Core?

Yes, in .NET Core 3.x, when you want to pass json from controller to client, it will camel-case all JSON output by default.

To avoid this, you can add the following setting in startup.cs ConfigureServices method:

services.AddMvc()
 .AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);

Since I added this setting before, the problem did not appear when I tested with your code. If I delete it, your problem will be reproduced.

So you have two solutions, change the field name to camel-case in js, or add the above code in startup.

0
On

OK, as always @YongquingYu got me on the right track. I am a 'nuffy' when it come to Ajax and Jquery. My issue, for reasons I don't understand was with capitalization, once I made the 'properties' lower case it worked. Does this have something to do with it being Asp.Net Core? Anyway my code (which is working as desired) is below:

@section Scripts{

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>

    <script>
        $(document).ready(function () {
            var events = [];
            $.ajax({
                type: "GET",
                url: "/Applications/GetEvents",
                success: function (data) {
                    $.each(data, function (i, v) {
                        events.push({
                            title: v.applicantContactName,
                            description: v.facility,
                            start: moment(v.start),
                            end: v.end != null ? moment(v.end) : null,
                            color: v.themeColor,
                            allDay: v.isFullDay
                        });
                    })

                    GenerateCalender(events);
                },
                error: function (error) {
                    alert('failed');
                }
            })

            function GenerateCalender(events) {
                $('#calender').fullCalendar('destroy');
                $('#calender').fullCalendar({
                    contentHeight: 400,
                    defaultDate: new Date(),
                    timeFormat: 'h(:mm)a',
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,basicWeek,basicDay,agenda'
                    },
                    eventLimit: true,
                    eventColor: '#378006',
                    events: events,
                    eventClick: function (calEvent, jsEvent, view) {
                        $('#myModal #eventTitle').text(calEvent.title);
                        var $description = $('<div/>');
                        $description.append($('<p/>').html('<b>Start: </b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
                        if (calEvent.end != null) {
                            $description.append($('<p/>').html('<b>End: </b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
                        }
                        $description.append($('<p/>').html('<b>Description: </b>' +
                            calEvent.description));
                        $('#myModal #pDetails').empty().html($description);

                        $('#myModal').modal();
                    }
                })
            }
        })
    </script>
}

// GET: Applications/CalendarView

public IActionResult CalendarView()
{
    return View();
}

public JsonResult GetEvents()
{
    using (WCCFacilityBookingsContext context = new WCCFacilityBookingsContext())
    {
        var events = context.BookingApplications.ToList();
        return Json(events);
    }
}