Jquery Full Calender Integrated With ASP.NET
Hello Guys, Welcome to Code2Night! Today, we have an exciting topic to discuss: "Jquery Full Calender Integrated with ASP.NET."
In this post, we will delve into the fascinating world of web development, where we'll explore how to seamlessly integrate the powerful jQuery Full Calendar plugin with the versatile ASP.NET framework.
As we all know, creating a visually appealing and user-friendly calendar is a crucial component of many web applications. With jQuery Full Calendar, we can effortlessly achieve this goal while leveraging the robust capabilities of ASP.NET.
Throughout this post, we'll guide you step-by-step on how to set up and integrate the jQuery Full Calendar plugin with ASP.NET, ensuring that you have a solid understanding of the process.
By the end of this post, you'll be equipped with the knowledge to build dynamic and interactive calendars that meet your specific requirements. We'll cover everything from installation and configuration to handling events and customization options.
So, without further ado, let's dive right in and explore the fascinating world of integrating jQuery Full Calendar with ASP.NET. Get ready to take your web development skills to new heights!
Step 1: Now we will add the following files to the Master Page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.css" rel="stylesheet" />
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/moment.min.js'></script>
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery.min.js'></script>
<script src="http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery-ui.custom.min.js"></script>
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/fullcalendar.min.js'></script>
STEP 2: Add the div
<section class="content" style="background-color:white">
<div class="row">
<div class="col-xs-12">
<div id="calendar" style="width: 1200px; margin-left: 105px;">
</div>
</div>
</div>
</section>
<!-- Add Event Modal -->
<div class="modal fade" id="addEventModal" tabindex="-1" role="dialog" aria-labelledby="addEventModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addEventModalLabel">Add Event</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="frm">
<div class="form-group">
<label for="eventStartDate">Start Date</label>
<input type="date" class="form-control" id="eventStartDate" name="startDate" required>
</div>
<div class="form-group">
<label for="eventStartTime">Start Time</label>
<input type="time" class="form-control" id="eventStartTime" name="startTime" required>
</div>
<div class="form-group">
<label for="eventEndTime">End Time</label>
<input type="time" class="form-control" id="eventEndTime" name="endTime" required>
</div>
<!-- Other event fields... -->
<button type="button" id="addEventForm" class="btn btn-primary">Add Event</button>
</form>
</div>
</div>
</div>
</div>
Step 3: Add the Script File
$(document).ready(function () {
$(document).ready(function () {
InitializeCalendar();
});
function InitializeCalendar() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "/Default.aspx/GetCalendarData",
dataType: "json",
success: function (data) {
$('#calendar').empty();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
//weekNumbers: true,
height: 600,
width: 100,
allDayText: 'Events',
selectable: true,
overflow: 'auto',
editable: true,
firstDay: 1,
slotEventOverlap: true,
dayClick: function (date, jsEvent, view) {
// Show a modal or form to add a new event
$('#addEventModal').modal('show'); // Assuming you have a modal with the ID 'addEventModal'
$('#eventStartDate').val(date.format()); // Pre-fill the selected date in the form
},
events: $.map(data.d, function (item, i) {
//-- here is the event details to show in calendar view.. the data is retrieved via ajax call will be accessed here
var eventStartDate = new Date(parseInt(item.slotStartTime.substr(6)));
var eventEndDate = new Date(parseInt(item.slotEndTime.substr(6)));
var event = new Object();
event.id = item.slotID;
//event.start = new Date(eventStartDate.getFullYear(), eventStartDate.getMonth(), eventStartDate.getDate(), eventStartDate.getHours(), 0, 0, 0);
//event.end = new Date(eventEndDate.getFullYear(), eventEndDate.getMonth(), eventEndDate.getDate(), eventEndDate.getHours() + 1, 0, 0, 0);
event.start = eventStartDate;
// event.end = eventEndDate;
event.title = formatAMPM(eventStartDate) + "-" + formatAMPM(eventEndDate);
//event.allDay = item.AllDayEvent;
event.backgroundColor = item.color;
event.allDay= true;
return event;
})
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//-- log error
}
});
}
$('#addEventForm').on('click', function (e) {
debugger;
var formData = $('#frm').serializeArray();
var newEvent = {
slotDate: new Date($('#eventStartDate').val()),
slotStartTime: $('#eventStartDate').val() + ' ' + $('#eventStartTime').val(),
slotEndTime: $('#eventStartDate').val() + ' ' + $('#eventEndTime').val(),
// Other event properties...
};
// Send the new event data to the server using Ajax
$.ajax({
url: 'Default.aspx/SaveEvent', // Replace with the actual server endpoint
method: 'POST',
data: JSON.stringify({ newEvent: newEvent }),
contentType: "application/json",
dataType: "json",
success: function (response) {
if (response.d=="success") {
// Event saved successfully
$('#calendar').fullCalendar('destroy');
$('#addEventModal').modal('hide');
$('#eventStartDate').val('');
$('#eventStartTime').val('');
$('#eventEndTime').val('');
InitializeCalendar();
} else {
// Handle error response
// Display error message, etc.
}
},
error: function () {
// Handle Ajax error
// Display error message, etc.
}
});
});
})
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
Step 4: Add the connection String
<connectionStrings>
<add name="connectionString" connectionString="data source=SHUBHAM\SQLEXPRESS; database=CrudMVC; integrated security=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Step 5: Add the Class CalendarEvents
public class CalendarEvents
{
public int slotID { get; set; }
public DateTime slotStartTime { get; set; }
public DateTime slotEndTime { get; set; }
public DateTime slotDate { get; set; }
public string EventDescription { get; set; }
public string Title { get; set; }
public string slotStatus { get; set; }
public int bookingID { get; set; }
public bool AllDayEvent { get; set; }
public string color { get; set; }
}
Step 6: Add the Web method
[WebMethod]
public static List<CalendarEvents> GetCalendarData()
{
//-- this is the webmethod that you will require to create to fetch data from database
return GetCalendarDataFromDatabase();
}
[WebMethod]
public static string SaveEvent(CalendarEvents newEvent)
{
try
{
// Validate and save the event in the database
// Example: DbContext.Events.Add(newEvent); DbContext.SaveChanges();
string constring = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("Insert into SlotMaster(SlotStatus,SlotStartTime,SlotEndTime,SlotDate)VALUES(@SlotStatus,@SlotStartTime,@SlotEndTime,@SlotDate)", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
cmd.Parameters.AddWithValue("@SlotStatus","Active");
cmd.Parameters.AddWithValue("@SlotStartTime", newEvent.slotStartTime);
cmd.Parameters.AddWithValue("@SlotEndTime", newEvent.slotEndTime);
cmd.Parameters.AddWithValue("@SlotDate", newEvent.slotDate);
cmd.ExecuteNonQuery();
con.Close();
}
}
return "success";
}
catch (Exception ex)
{
return "failure";
}
}
private static List<CalendarEvents> GetCalendarDataFromDatabase()
{
List<CalendarEvents> CalendarList = new List<CalendarEvents>();
string constring = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
string strQuery = "Select * FROM SlotMaster where slotStatus='ACTIVE' ";
using (SqlCommand cmd = new SqlCommand(strQuery, con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
// ds = ClsDAL.QueryEngine(strQuery, "SlotMaster");
DataTable dt = new DataTable();
sda.Fill(dt);
//dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
CalendarEvents Calendar = new CalendarEvents();
Calendar.slotID = Convert.ToInt32(dt.Rows[i]["slotID"]);
Calendar.slotDate = Convert.ToDateTime(dt.Rows[i]["slotDate"]);
Calendar.slotStatus = dt.Rows[i]["slotStatus"].ToString();
Calendar.slotStartTime = Convert.ToDateTime(dt.Rows[i]["slotStartTime"]);
Calendar.slotEndTime = Convert.ToDateTime(dt.Rows[i]["slotEndTime"]);
if (Calendar.slotStatus == "ACTIVE")
{
Calendar.color = "green";
}
else
{
// Calendar.color = "white";
}
CalendarList.Add(Calendar);
}
}
}
}
return CalendarList;
}
STEP 7: Complete the code of the script
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Summernote._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.css" rel="stylesheet" />
<script src='https://fullcalendar.io/js/fullcalendar-2.1.1/lib/moment.min.js'></script>
<script src='https://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery.min.js'></script>
<script src="https://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery-ui.custom.min.js"></script>
<script src='https://fullcalendar.io/js/fullcalendar-2.1.1/fullcalendar.min.js'></script>
<link href="Content/bootstrap.css" rel="stylesheet" />
<script src="Scripts/bootstrap.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<section class="content" style="background-color:white">
<div class="row">
<div class="col-xs-12">
<div id="calendar" style="width: 1200px; margin-left: 105px;">
</div>
</div>
</div>
<!-- Add Event Modal -->
<div class="modal fade" id="addEventModal" tabindex="-1" role="dialog" aria-labelledby="addEventModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addEventModalLabel">Add Event</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="frm">
<div class="form-group">
<label for="eventStartDate">Start Date</label>
<input type="date" class="form-control" id="eventStartDate" name="startDate" required>
</div>
<div class="form-group">
<label for="eventStartTime">Start Time</label>
<input type="time" class="form-control" id="eventStartTime" name="startTime" required>
</div>
<div class="form-group">
<label for="eventEndTime">End Time</label>
<input type="time" class="form-control" id="eventEndTime" name="endTime" required>
</div>
<!-- Other event fields... -->
<button type="button" id="addEventForm" class="btn btn-primary">Add Event</button>
</form>
</div>
</div>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function () {
$(document).ready(function () {
InitializeCalendar();
});
function InitializeCalendar() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "/Default.aspx/GetCalendarData",
dataType: "json",
success: function (data) {
$('#calendar').empty();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
//weekNumbers: true,
height: 600,
width: 100,
allDayText: 'Events',
selectable: true,
overflow: 'auto',
editable: true,
firstDay: 1,
slotEventOverlap: true,
dayClick: function (date, jsEvent, view) {
// Show a modal or form to add a new event
$('#addEventModal').modal('show'); // Assuming you have a modal with the ID 'addEventModal'
$('#eventStartDate').val(date.format()); // Pre-fill the selected date in the form
},
events: $.map(data.d, function (item, i) {
//-- here is the event details to show in calendar view.. the data is retrieved via ajax call will be accessed here
var eventStartDate = new Date(parseInt(item.slotStartTime.substr(6)));
var eventEndDate = new Date(parseInt(item.slotEndTime.substr(6)));
var event = new Object();
event.id = item.slotID;
//event.start = new Date(eventStartDate.getFullYear(), eventStartDate.getMonth(), eventStartDate.getDate(), eventStartDate.getHours(), 0, 0, 0);
//event.end = new Date(eventEndDate.getFullYear(), eventEndDate.getMonth(), eventEndDate.getDate(), eventEndDate.getHours() + 1, 0, 0, 0);
event.start = eventStartDate;
// event.end = eventEndDate;
event.title = formatAMPM(eventStartDate) + "-" + formatAMPM(eventEndDate);
//event.allDay = item.AllDayEvent;
event.backgroundColor = item.color;
event.allDay= true;
return event;
})
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//-- log error
}
});
}
$('#addEventForm').on('click', function (e) {
debugger;
var formData = $('#frm').serializeArray();
var newEvent = {
slotDate: new Date($('#eventStartDate').val()),
slotStartTime: $('#eventStartDate').val() + ' ' + $('#eventStartTime').val(),
slotEndTime: $('#eventStartDate').val() + ' ' + $('#eventEndTime').val(),
// Other event properties...
};
// Send the new event data to the server using Ajax
$.ajax({
url: 'Default.aspx/SaveEvent', // Replace with the actual server endpoint
method: 'POST',
data: JSON.stringify({ newEvent: newEvent }),
contentType: "application/json",
dataType: "json",
success: function (response) {
if (response.d=="success") {
// Event saved successfully
$('#calendar').fullCalendar('destroy');
$('#addEventModal').modal('hide');
$('#eventStartDate').val('');
$('#eventStartTime').val('');
$('#eventEndTime').val('');
InitializeCalendar();
} else {
// Handle error response
// Display error message, etc.
}
},
error: function () {
// Handle Ajax error
// Display error message, etc.
}
});
});
})
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
</script>
</asp:Content>
step 8: complete the code of BookingCalendar
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; namespace Summernote { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static List<CalendarEvents> GetCalendarData() { //-- this is the webmethod that you will require to create to fetch data from database return GetCalendarDataFromDatabase(); } [WebMethod] public static string SaveEvent(CalendarEvents newEvent) { try { // Validate and save the event in the database // Example: DbContext.Events.Add(newEvent); DbContext.SaveChanges(); string constring = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString; using (SqlConnection con = new SqlConnection(constring)) { using (SqlCommand cmd = new SqlCommand("Insert into SlotMaster(SlotStatus,SlotStartTime,SlotEndTime,SlotDate)VALUES(@SlotStatus,@SlotStartTime,@SlotEndTime,@SlotDate)", con)) { cmd.CommandType = CommandType.Text; con.Open(); cmd.Parameters.AddWithValue("@SlotStatus","Active"); cmd.Parameters.AddWithValue("@SlotStartTime", newEvent.slotStartTime); cmd.Parameters.AddWithValue("@SlotEndTime", newEvent.slotEndTime); cmd.Parameters.AddWithValue("@SlotDate", newEvent.slotDate); cmd.ExecuteNonQuery(); con.Close(); } } return "success"; } catch (Exception ex) { return "failure"; } } private static List<CalendarEvents> GetCalendarDataFromDatabase() { List<CalendarEvents> CalendarList = new List<CalendarEvents>(); string constring = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString; using (SqlConnection con = new SqlConnection(constring)) { string strQuery = "Select * FROM SlotMaster where slotStatus='ACTIVE' "; using (SqlCommand cmd = new SqlCommand(strQuery, con)) { cmd.CommandType = CommandType.Text; using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); // ds = ClsDAL.QueryEngine(strQuery, "SlotMaster"); DataTable dt = new DataTable(); sda.Fill(dt); //dt = ds.Tables[0]; for (int i = 0; i < dt.Rows.Count; i++) { CalendarEvents Calendar = new CalendarEvents(); Calendar.slotID = Convert.ToInt32(dt.Rows[i]["slotID"]); Calendar.slotDate = Convert.ToDateTime(dt.Rows[i]["slotDate"]); Calendar.slotStatus = dt.Rows[i]["slotStatus"].ToString(); Calendar.slotStartTime = Convert.ToDateTime(dt.Rows[i]["slotStartTime"]); Calendar.slotEndTime = Convert.ToDateTime(dt.Rows[i]["slotEndTime"]); if (Calendar.slotStatus == "ACTIVE") { Calendar.color = "green"; } else { // Calendar.color = "white"; } CalendarList.Add(Calendar); } } } } return CalendarList; } public class CalendarEvents { public int slotID { get; set; } public DateTime slotStartTime { get; set; } public DateTime slotEndTime { get; set; } public DateTime slotDate { get; set; } public string EventDescription { get; set; } public string Title { get; set; } public string slotStatus { get; set; } public int bookingID { get; set; } public bool AllDayEvent { get; set; } public string color { get; set; } } } }