Header Ads

ASP.NET MVC5: Full Calendar JQuery Plugin

Calendar is an important part in improving user visibility for the announced holidays or for meeting scheduling display. Displaying the calendar on a full page makes the user visibility more interactive.

Today, I shall be demonstrating Full Calendar JQuery Plugin in ASP.NET MVC5. Full Calendar JQuery Plugin is simple to use and provides a variety of options for customization for better user interactivity.


Prerequisites:

Following are some prerequisites before you proceed further in this tutorial:
  1. Knowledge about ASP.NET MVC5.
  2. Knowledge about JQuery
  3. Knowledge about HTML.
  4. Knowledge about Javascript.
  5. Knowledge about AJAX.
  6. Knowledge about CSS.
  7. Knowledge about Bootstrap.
  8. Knowledge about C# programming.
  9. Knowledge about C# LINQ.
You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is developed in Microsoft Visual Studio 2015 Enterprise. I am using 2017 public holidays for Pakistan as announce by the Pakistan Government.

Download Now! or Full Calendar 3.9.0 Upgrade

Let's begin now.

1) Create a new MVC5 web application project and name it "MVC5FullCalandarPlugin".
2) Open "Views\Shared\_Layout.cshtml" file and replace following code in it i.e.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />

    <!-- qTip -->
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.css" />

    <!-- Full Calendar -->
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.9.1/fullcalendar.min.css" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.9.1/fullcalendar.print.css" media="print" />

    @* Custom *@
    @Styles.Render("~/Content/css/custom-style")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <center>
                <p><strong>Copyright &copy; @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
            </center>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")

    <!-- Include moment-->
    <script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>

    <!-- qTip -->
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.js"></script>

    <!-- Full Calendar -->
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.9.1/fullcalendar.min.js"></script>
    @Scripts.Render("~/bundles/Script-calendar")

    @RenderSection("scripts", required: false)
</body>
</html>

In the above code, I have simply created the basic layout structure of this web project and I have also added reference to the Full Calendar JQuery Plugin.

3) Create a new "Models\HomeViewModels.cs" file and replace following code in it i.e.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace MVC5FullCalandarPlugin.Models
{
    public class PublicHoliday
    {
        public int Sr { get; set; }
        public string Title { get; set; }
        public string Desc { get; set; }
        public string Start_Date { get; set; }
        public string End_Date { get; set; }
    }
}

In the above code, I have simply created our view model which will map the data from text file into main memory as object

4) Now create "Controllers\HomeController.cs" file and replace following code in it i.e.

using MVC5FullCalandarPlugin.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace MVC5FullCalandarPlugin.Controllers
{
    public class HomeController : Controller
    {
        #region Index method

        /// <summary>
        /// GET: Home/Index method.
        /// </summary>
        /// <returns>Returns - index view page</returns> 
        public ActionResult Index()
        {
            // Info.
            return this.View();
        }

        #endregion

        #region Get Calendar data method.

        /// <summary>
        /// GET: /Home/GetCalendarData
        /// </summary>
        /// <returns>Return data</returns>
        public ActionResult GetCalendarData()
        {
            // Initialization.
            JsonResult result = new JsonResult();

            try
            {
                // Loading.
                List<PublicHoliday> data = this.LoadData();

                // Processing.
                result = this.Json(data, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }

            // Return info.
            return result;
        }

        #endregion

        #region Helpers

        #region Load Data

        /// <summary>
        /// Load data method.
        /// </summary>
        /// <returns>Returns - Data</returns>
        private List<PublicHoliday> LoadData()
        {
            // Initialization.
            List<PublicHoliday> lst = new List<PublicHoliday>();

            try
            {
                // Initialization.
                string line = string.Empty;
                string srcFilePath = "Content/files/PublicHoliday.txt";
                var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
                var fullPath = Path.Combine(rootPath, srcFilePath);
                string filePath = new Uri(fullPath).LocalPath;
                StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));

                // Read file.
                while ((line = sr.ReadLine()) != null)
                {
                    // Initialization.
                    PublicHoliday infoObj = new PublicHoliday();
                    string[] info = line.Split(',');

                    // Setting.
                    infoObj.Sr = Convert.ToInt32(info[0].ToString());
                    infoObj.Title = info[1].ToString();
                    infoObj.Desc = info[2].ToString();
                    infoObj.Start_Date = info[3].ToString();
                    infoObj.End_Date = info[4].ToString();

                    // Adding.
                    lst.Add(infoObj);
                }

                // Closing.
                sr.Dispose();
                sr.Close();
            }
            catch (Exception ex)
            {
                // info.
                Console.Write(ex);
            }

            // info.
            return lst;
        }

        #endregion

        #endregion
    }
}

In the above code, I have created a simple index() action methods along with a helper method LoadData() for data loading from text file and finally GetCalendarData() action method which will be called by Full Calendar JQuery Plugin via ajax call method in order to map data on the calendar.

5) Create a new "Scripts\script-custom-calendar.js" script file and replace following code in it i.e.

$(document).ready(function ()
{
    $('#calendar').fullCalendar({
        header:
        {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        buttonText: {
            today: 'today',
            month: 'month',
            week: 'week',
            day: 'day'
        },

        events: function (start, end, timezone, callback)
        {
            $.ajax({
                url: '/Home/GetCalendarData',
                type: "GET",
                dataType: "JSON",

                success: function (result)
                {
                    var events = [];

                    $.each(result, function (i, data)
                    {
                        events.push(
                       {
                           title: data.Title,
                           description: data.Desc,
                           start: moment(data.Start_Date).format('YYYY-MM-DD'),
                           end: moment(data.End_Date).format('YYYY-MM-DD'),
                           backgroundColor: "#9501fc",
                           borderColor: "#fc0101"
                       });
                    });

                    callback(events);
                }
            });
        },

        eventRender: function (event, element)
        {
            element.qtip(
            {
                content: event.description
            });
        },

        editable: false
    });
});

Let's break down the code chunk by chunk. Inside the fullCalendar(...) method, firstly. header properties are being set i.e where will the calendar top buttons will be aligned and also the alignment of the calendar title is being set along with the button text of the calendar header i.e.

        header:
        {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        buttonText: {
            today: 'today',
            month: 'month',
            week: 'week',
            day: 'day'
        },

Then I call the GetCalendarData() server side method via ajax call and after successfully receiving the data. I simply set default calendar options and also set an extra property "description", which I will be using as tool tip on the calendar when someone hover the mouse over the displayed event i.e.

       events: function (start, end, timezone, callback)
        {
            $.ajax({
                url: '/Home/GetCalendarData',
                type: "GET",
                dataType: "JSON",

                success: function (result)
                {
                    var events = [];

                    $.each(result, function (i, data)
                    {
                        events.push(
                       {
                           title: data.Title,
                           description: data.Desc,
                           start: moment(data.Start_Date).format('YYYY-MM-DD'),
                           end: moment(data.End_Date).format('YYYY-MM-DD'),
                           backgroundColor: "#9501fc",
                           borderColor: "#fc0101"
                       });
                    });

                    callback(events);
                }
            });
        },

Now to render my tool tip description per calendar holiday event, I will be adding eventRender(...)  property and inside that property I will be calling qTip Jquery plugin in order to assign tool tip description to each calendar holiday event i.e.

        eventRender: function (event, element)
        {
            element.qtip(
            {
                content: event.description
            });
        },

6) Create "Views\Home\_CalendarPartial.cshtml" & "Views\Home\Index.cshtml" files and replace following code in it i.e.

Views\Home\_CalendarPartial.cshtml



<div class="row">
    <div class="col-xs-9 col-xs-push-2">
        <div class="box box-primary">
            <div class="box-body no-padding">
                <!-- THE CALENDAR -->
                <div id="calendar"></div>
            </div><!-- /.box-body -->
        </div><!-- /. box -->
    </div><!-- /.col -->
</div>

View\Home\Index.cshtml



@{
    ViewBag.Title = "ASP.NET MVC5 - Full Calendar JQuery Plugin";
}

<div class="row">
    <div class="panel-heading">
        <div class="col-md-8  custom-heading3">
            <h3>
                <i class="fa fa-calendar"></i>
                <span>ASP.NET MVC5 - Full Calendar JQuery Plugin</span>
            </h3>
        </div>
    </div>
</div>

<div class="row">
    <section class="col-md-12 col-md-push-0">
        @Html.Partial("_CalendarPartial")
    </section>
</div>

In the above code, I have simply create the view code for the page which will display the calendar. I have divided the page into two parts for better manageability.

7) Execute the project and you will be able to see following i.e.


Conclusion

In this article, you will learn to use Full Calendar JQuery Plugin basic settings. You will also learn to integrate Full Calendar JQuery Plugin into asp.net mvc5 project. You will learn about data passing to front view through ajax call and you will learn to represent your data on full page calendar. 

3 comments: