Currently working on the jquery fullcalendar, I’ve been unable to add events to it from code behind.
I’ve tried all of these possible solutions but none of them worked for me:
- Fullcalendar/Fetching JSON feed(Edited)
- fullCalendar events not showing even though correct JSON feed
- JQuery FullCalendar not displaying events from aspx page
This is my code
[WebMethod]
JavaScript
x
37
37
1
public static String TestOnWebService()
2
{
3
int i = 1;
4
5
string myJsonString = "";
6
List<object> myList = new List<object>();
7
dt = db.getPublicHolidays();
8
9
foreach (DataRow dr in dt.Rows)
10
{
11
var id = i;
12
var title = dr["name"].ToString();
13
var start = dr["startDate"].ToString();
14
var end = dr["endDate"].ToString();
15
16
17
//Convert Implicity typed var to Date Time
18
DateTime RealStartDate = Convert.ToDateTime(start);
19
DateTime RealEndDate = Convert.ToDateTime(end);
20
21
22
//Convert Date Time to ISO
23
String SendStartDate = RealStartDate.ToString("s");
24
String SendEndDate = RealEndDate.ToString("s");
25
26
27
Events t_table = new Events(id, title, start, end);
28
29
myList.Add(t_table);
30
i++;
31
}
32
33
myJsonString = (new JavaScriptSerializer()).Serialize(myList);
34
return myJsonString;
35
}
36
}
37
and my events class
JavaScript
1
16
16
1
public class Events
2
{
3
public int id { get; set; }
4
public String title { get; set; }
5
public String start { get; set; }
6
public String end { get; set; }
7
8
public Events(int id2, String I, String t, String ds)
9
{
10
this.id = id2;
11
this.title = I;
12
this.start = t;
13
this.end = ds;
14
}
15
}
16
Here is the front end code
JavaScript
1
31
31
1
events: function (start, end, callback) {
2
$.ajax({
3
type: "POST", //WebMethods will not allow GET
4
url: '<%= ResolveUrl("EmpHolidays.aspx/TestOnWebService") %>', //url of a webmethod - example below
5
contentType: "application/json; charset=utf-8",
6
dataType: "json",
7
success: function (doc) {
8
var events = []; //javascript event object created here
9
var obj = $.parseJSON(doc.d); //.net returns json wrapped in "d"
10
11
for(var i=0;i<obj.length;i++){
12
console.log(obj[i]['id']);
13
console.log(obj[i]['title']);
14
console.log(obj[i]['start']);
15
console.log(obj[i]['end']);
16
}
17
18
19
$(obj.event).each(function () { //yours is obj.calevent
20
events.push({
21
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
22
start: $(this).attr('start'), // will be parsed into DateTime object
23
end: $(this).attr('end'),
24
id: $(this).attr('id')
25
});
26
});
27
callback(events);
28
}
29
});
30
}
31
This is the result I get
Advertisement
Answer
SO AFTER THREE DAYS OF STRUGGLE, I GOT IT TO WORK! I added events from database to add to the jquery fullcalender. this is what solved my problem! Here is my code
My html and javascript code
JavaScript
1
571
571
1
<!-- Main content -->
2
<section class="content">
3
<div class="row">
4
<div class="col-md-3">
5
<div class="box box-solid">
6
<div class="box-header with-border">
7
<h4 class="box-title">Draggable Events</h4>
8
</div>
9
<div class="box-body">
10
<!-- the events -->
11
<div id="external-events">
12
13
14
<div runat="server" id="check">
15
16
</div>
17
18
19
20
<div class="checkbox">
21
<label for="drop-remove">
22
<input type="checkbox" id="drop-remove">
23
remove after drop
24
</label>
25
</div>
26
</div>
27
</div>
28
<!-- /.box-body -->
29
</div>
30
<!-- /. box -->
31
<div class="box box-solid">
32
<div class="box-header with-border">
33
<h3 class="box-title">Create Event</h3>
34
</div>
35
<div class="box-body">
36
<div class="btn-group" style="width: 100%; margin-bottom: 10px;">
37
<!--<button type="button" id="color-chooser-btn" class="btn btn-info btn-block dropdown-toggle" data-toggle="dropdown">Color <span class="caret"></span></button>-->
38
<ul class="fc-color-picker" id="color-chooser">
39
<li><a class="text-aqua" href="#"><i class="fa fa-square"></i></a></li>
40
<li><a class="text-blue" href="#"><i class="fa fa-square"></i></a></li>
41
<li><a class="text-light-blue" href="#"><i class="fa fa-square"></i></a></li>
42
<li><a class="text-teal" href="#"><i class="fa fa-square"></i></a></li>
43
<li><a class="text-yellow" href="#"><i class="fa fa-square"></i></a></li>
44
<li><a class="text-orange" href="#"><i class="fa fa-square"></i></a></li>
45
<li><a class="text-green" href="#"><i class="fa fa-square"></i></a></li>
46
<li><a class="text-lime" href="#"><i class="fa fa-square"></i></a></li>
47
<li><a class="text-red" href="#"><i class="fa fa-square"></i></a></li>
48
<li><a class="text-purple" href="#"><i class="fa fa-square"></i></a></li>
49
<li><a class="text-fuchsia" href="#"><i class="fa fa-square"></i></a></li>
50
<li><a class="text-muted" href="#"><i class="fa fa-square"></i></a></li>
51
<li><a class="text-navy" href="#"><i class="fa fa-square"></i></a></li>
52
</ul>
53
</div>
54
<!-- /btn-group -->
55
<div class="input-group">
56
<input id="new-event" type="text" class="form-control" placeholder="Event Title">
57
58
<div class="input-group-btn">
59
<button id="add-new-event" type="button" class="btn btn-primary btn-flat">Add</button>
60
</div>
61
<!-- /btn-group -->
62
</div>
63
<!-- /input-group -->
64
</div>
65
</div>
66
67
<br />
68
<button onclick="saveEvent();">Save</button>
69
</div>
70
<!-- /.col -->
71
<div class="col-md-9">
72
<div class="box box-primary">
73
<div class="box-body no-padding">
74
<!-- THE CALENDAR -->
75
<div id="calendar"></div>
76
</div>
77
<!-- /.box-body -->
78
</div>
79
<!-- /. box -->
80
</div>
81
<!-- /.col -->
82
</div>
83
<!-- /.row -->
84
</section>
85
<!-- /.content -->
86
87
</ContentTemplate>
88
89
</asp:UpdatePanel>
90
<!-- jQuery 2.2.0 -->
91
92
<!-- Page specific script -->
93
<script>
94
var data2="";
95
var startDateFinal="";
96
var endDateFinal="";
97
var eventNameFinal="";
98
99
$(function () {
100
101
/* initialize the external events
102
-----------------------------------------------------------------*/
103
function ini_events(ele) {
104
ele.each(function () {
105
106
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
107
// it doesn't need to have a start or end
108
var eventObject = {
109
title: $.trim($(this).text())
110
};
111
112
113
114
// store the Event Object in the DOM element so we can get to it later
115
$(this).data('eventObject', eventObject);
116
117
// make the event draggable using jQuery UI
118
$(this).draggable({
119
zIndex: 1070,
120
revert: true, // will cause the event to go back to its
121
revertDuration: 0 // original position after the drag
122
});
123
124
125
126
});
127
}
128
129
ini_events($('#external-events div.external-event'));
130
131
/* initialize the calendar
132
-----------------------------------------------------------------*/
133
//Date for the calendar events (dummy data)
134
var date = new Date();
135
var d = date.getDate(),
136
m = date.getMonth(),
137
y = date.getFullYear();
138
$('#calendar').fullCalendar({
139
header: {
140
left: 'prev,next today',
141
center: 'title',
142
right: 'month,agendaWeek,agendaDay'
143
},
144
<%--events: {
145
$.ajax({
146
type: "POST",
147
url: '<%= ResolveUrl("EmpHolidays.aspx/TestOnWebService") %>',
148
data: "{}",
149
contentType: "application/json; charset=utf-8",
150
dataType: "json",
151
success: function (doc) {
152
alert("Success");
153
var events = [];
154
alert(doc.d);
155
var obj = $.parseJSON(doc.d);
156
for(var i=0;i<obj.length;i++){
157
158
159
title: 'All Day Event',
160
start: new Date(y, m, 1),
161
backgroundColor: "#f56954", //red
162
borderColor: "#f56954" //red
163
164
165
console.log(obj[i]['id']);
166
console.log(obj[i]['title']);
167
console.log(obj[i]['start']);
168
console.log(obj[i]['end']);
169
}
170
171
172
//$(obj.event).each(function () {
173
// events.push({
174
// id: $(this).attr('id'),
175
// title: $(this).attr('title'),
176
// start: $(this).attr('start'),
177
// end: $(this).attr('end'),
178
// backgroundColor: "#0073b7",
179
// borderColor: "#0073b7"
180
// });
181
182
183
184
// });
185
//callback(events);
186
callback && callback(events);
187
},
188
error: function(xhr, status, error) {
189
alert(xhr.responseText);
190
}
191
});
192
events: [
193
{
194
title: 'All Day Event',
195
start: new Date(y, m, 1),
196
backgroundColor: "#f56954", //red
197
borderColor: "#f56954" //red
198
},
199
{
200
title: 'Long Event',
201
start: new Date(y, m, d - 5),
202
end: new Date(y, m, d - 2),
203
backgroundColor: "#f39c12", //yellow
204
borderColor: "#f39c12" //yellow
205
},
206
{
207
title: 'Meeting',
208
start: new Date(y, m, d, 10, 30),
209
allDay: false,
210
backgroundColor: "#0073b7", //Blue
211
borderColor: "#0073b7" //Blue
212
},
213
{
214
title: 'Lunch',
215
start: new Date(y, m, d, 12, 0),
216
end: new Date(y, m, d, 14, 0),
217
allDay: false,
218
backgroundColor: "#00c0ef", //Info (aqua)
219
borderColor: "#00c0ef" //Info (aqua)
220
},
221
{
222
title: 'Birthday Party',
223
start: new Date(y, m, d + 1, 19, 0),
224
end: new Date(y, m, d + 1, 22, 30),
225
allDay: false,
226
backgroundColor: "#00a65a", //Success (green)
227
borderColor: "#00a65a" //Success (green)
228
},
229
{
230
title: 'Click for Google',
231
start: new Date(y, m, 28),
232
end: new Date(y, m, 29),
233
url: 'http://google.com/',
234
backgroundColor: "#3c8dbc", //Primary (light-blue)
235
borderColor: "#3c8dbc" //Primary (light-blue)
236
}
237
]
238
239
240
$.ajax({
241
type: "GET",
242
url: '<%= ResolveUrl("EmpHolidays.aspx/TestOnWebService") %>',
243
data: {
244
name: $(this).attr('name'),
245
startDate: $(this).attr('startDate'),
246
endDate: $(this).attr('endDate'),
247
},
248
success: function(events)
249
{
250
$('#calendar').fullCalendar('removeEvents');
251
$('#calendar').fullCalendar('addEventSource', events);
252
$('#calendar').fullCalendar('rerenderEvents' );
253
}
254
});
255
256
},--%>
257
258
// events: function () {
259
// var data = getData();
260
// console.log(data);
261
262
// //var events = [];
263
// // $.each(data, function (key, val) {
264
// // events.push({
265
// // title: val.title,
266
// // start: val.start,
267
// // end: val.end
268
// // });
269
// // });
270
271
// //callback(events);
272
273
//},
274
275
276
277
buttonText: {
278
today: 'today',
279
month: 'month',
280
week: 'week',
281
day: 'day'
282
},
283
284
eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc) {
285
debugger;
286
if (event.forceAllDay && !allDay) {
287
revertFunc();
288
} else {
289
if (!confirm('Move event?')) {
290
revertFunc();
291
} else {
292
console.log(event.id);
293
}
294
}
295
},
296
297
eventDrop: function (event, delta, revertFunc) {
298
//inner column movement drop so get start and call the ajax function......
299
//debugger;
300
console.log(event.start.format());
301
console.log(event.id);
302
var defaultDuration = moment.duration($('#calendar').fullCalendar('option', 'defaultTimedEventDuration'));
303
var end = event.end || event.start.clone().add(defaultDuration);
304
305
var n = 1;
306
var dateMnsFive2 = moment(end).subtract(n , 'day');
307
var date2 = dateMnsFive2.format("YYYY-MM-DD");
308
309
console.log('end is ' + date2);
310
311
//alert(event.title + " was dropped on " + event.start.format());
312
313
//***********************************
314
startDateFinal = event.start.format();
315
endDateFinal = date2;
316
eventNameFinal = event.title;
317
//**********************************
318
319
320
321
},
322
editable: true,
323
droppable: true, // this allows things to be dropped onto the calendar !!!
324
325
drop: function (date, event, allDay) { // this function is called when something is dropped
326
327
console.clear();
328
console.log("dropped");
329
330
331
console.log(date.format());
332
333
334
var defaultDuration = moment.duration($('#calendar').fullCalendar('option', 'defaultTimedEventDuration'));
335
var end = date.clone().add(defaultDuration); // on drop we only have date given to us
336
console.log('end is ' + end.format());
337
338
339
340
341
// retrieve the dropped element's stored Event Object
342
var originalEventObject = $(this).data('eventObject');
343
console.log(originalEventObject["title"]);
344
345
346
347
//***********************************
348
startDateFinal = date.format();
349
endDateFinal = end.format();
350
eventNameFinal = originalEventObject["title"];
351
//**********************************
352
353
354
355
356
// we need to copy it, so that multiple events don't have a reference to the same object
357
var copiedEventObject = $.extend({}, originalEventObject);
358
359
360
361
// assign it the date that was reported
362
copiedEventObject.start = date;
363
copiedEventObject.allDay = allDay;
364
365
copiedEventObject.backgroundColor = $(this).css("background-color");
366
copiedEventObject.borderColor = $(this).css("border-color");
367
368
// render the event on the calendar
369
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
370
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
371
372
// is the "remove after drop" checkbox checked?
373
if ($('#drop-remove').is(':checked')) {
374
// if so, remove the element from the "Draggable Events" list
375
$(this).remove();
376
}
377
378
},
379
380
eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
381
382
383
384
var n = 1;
385
var dateMnsFive = moment(event.end.format()).subtract(n , 'day');
386
var date = dateMnsFive.format("YYYY-MM-DD");
387
alert(event.title + " end is now " + date);
388
389
//*************************************
390
eventNameFinal = event.title;
391
endDateFinal = date;
392
//*************************************
393
394
395
},
396
events: function (start, end, callback) {
397
$.ajax({
398
type: "POST", //WebMethods will not allow GET
399
url: '<%= ResolveUrl("EmpHolidays.aspx/TestOnWebService") %>', //url of a webmethod - example below
400
contentType: "application/json; charset=utf-8",
401
dataType: "json",
402
success: function (doc) {
403
var events = []; //javascript event object created here
404
var obj = $.parseJSON(doc.d); //.net returns json wrapped in "d"
405
406
407
408
for(var i=0;i<obj.length;i++){
409
console.log(obj[i]['id']);
410
console.log(obj[i]['title']);
411
console.log(obj[i]['start']);
412
console.log(obj[i]['end']);
413
414
addCalanderEvent(obj[i]['id'],obj[i]['start'],obj[i]['end'],obj[i]['title']);
415
416
}
417
418
419
420
//callback(events);
421
}
422
});
423
}
424
<%--events: {
425
type: "POST",
426
url: '<%= ResolveUrl("EmpHolidays.aspx/TestOnWebService") %>',
427
contentType: "application/json; charset=utf-8",
428
dataType: "json",
429
data: {
430
431
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
432
start: $(this).attr('start'), // will be parsed into DateTime object
433
end: $(this).attr('end'),
434
id: $(this).attr('id')
435
},
436
error: function() {
437
alert('there was an error while fetching events!');
438
},
439
color: 'yellow', // a non-ajax option
440
textColor: 'black' // a non-ajax option
441
}--%>
442
443
});
444
445
446
447
448
/* ADDING EVENTS */
449
var currColor = "#3c8dbc"; //Red by default
450
//Color chooser button
451
var colorChooser = $("#color-chooser-btn");
452
$("#color-chooser > li > a").click(function (e) {
453
e.preventDefault();
454
//Save color
455
currColor = $(this).css("color");
456
//Add color effect to button
457
$('#add-new-event').css({"background-color": currColor, "border-color": currColor});
458
});
459
$("#add-new-event").click(function (e) {
460
e.preventDefault();
461
//Get value and make sure it is not null
462
var val = $("#new-event").val();
463
if (val.length == 0) {
464
return;
465
}
466
467
//Create events
468
var event = $("<div />");
469
event.css({"background-color": currColor, "border-color": currColor, "color": "#fff"}).addClass("external-event");
470
event.html(val);
471
$('#external-events').prepend(event);
472
473
//Add draggable funtionality
474
ini_events(event);
475
476
//Remove event from text input
477
$("#new-event").val("");
478
});
479
});
480
481
482
483
function saveEvent(){
484
console.clear();
485
console.log(startDateFinal +" - "+ endDateFinal+" - "+eventNameFinal);
486
487
$.ajax({
488
type: "POST",
489
url: '<%= ResolveUrl("EmpHolidays.aspx/saveEvent") %>',
490
data: "{'startYear':'" + startDateFinal + "', 'endYear':'" + endDateFinal + "', 'eventName':'" + eventNameFinal + "'}",
491
contentType: "application/json; charset=utf-8",
492
dataType: 'json',
493
success: function (response) {
494
if (response.d) {
495
debugger;
496
}
497
else {
498
debugger;
499
}
500
},
501
failure: function (response) {
502
debugger;
503
}
504
});
505
}
506
507
function getData() {
508
509
var data3;
510
$.ajax({
511
type: "POST",
512
url: '<%= ResolveUrl("EmpHolidays.aspx/TestOnWebService") %>',
513
data: "{}",
514
contentType: "application/json; charset=utf-8",
515
dataType: "json",
516
async:false,
517
success: function (doc) {
518
519
data3 = $.parseJSON(doc.d);
520
data3 = JSON.stringify(data3)
521
522
},
523
error: function(xhr, status, error) {
524
alert(xhr.responseText);
525
}
526
});
527
528
529
530
return data3;
531
532
533
}
534
535
536
function addCalanderEvent(id, start, end, title)
537
{
538
539
console.log(id + start + end + title);
540
541
var eventObject = {
542
title: title,
543
start: start,
544
end: end,
545
id: id,
546
allDay: true
547
};
548
549
$('#calendar').fullCalendar('renderEvent', eventObject, true);
550
return eventObject;
551
}
552
553
</script>
554
555
<script src="../plugins/jQuery/jQuery-2.2.0.min.js"></script>
556
<!-- Bootstrap 3.3.5 -->
557
<script src="../bootstrap/js/bootstrap.min.js"></script>
558
<!-- jQuery UI 1.11.4 -->
559
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
560
<!-- Slimscroll -->
561
<script src="../plugins/slimScroll/jquery.slimscroll.min.js"></script>
562
<!-- FastClick -->
563
<script src="../plugins/fastclick/fastclick.js"></script>
564
<!-- AdminLTE App -->
565
<script src="../dist/js/app.min.js"></script>
566
<!-- AdminLTE for demo purposes -->
567
<script src="../dist/js/demo.js"></script>
568
<!-- fullCalendar 2.2.5 -->
569
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
570
<script src="../plugins/fullcalendar/fullcalendar.min.js"></script>
571
Here is the code behind function which returns json data from db
JavaScript
1
43
43
1
[WebMethod]
2
public static String TestOnWebService()
3
{
4
int i = 1;
5
6
string myJsonString = "";
7
List<object> myList = new List<object>();
8
dt = db.getPublicHolidays();
9
10
foreach (DataRow dr in dt.Rows)
11
{
12
var id = i;
13
var title = dr["name"].ToString();
14
var start = dr["startDate"].ToString();
15
var end = dr["endDate"].ToString();
16
17
18
//Convert Implicity typed var to Date Time
19
DateTime RealStartDate = Convert.ToDateTime(start);
20
DateTime RealEndDate = Convert.ToDateTime(end);
21
22
23
//Convert Date Time to ISO
24
String SendStartDate = RealStartDate.ToString("s");
25
String SendEndDate = RealEndDate.ToString("s");
26
27
//string start2 = ((RealStartDate.Ticks - 621355968000000000) / 10000000).ToString();
28
//string end2 = ((RealEndDate.Ticks - 621355968000000000) / 10000000).ToString();
29
30
Events t_table = new Events(id, title, SendStartDate, SendEndDate);
31
32
33
myList.Add(t_table);
34
i++;
35
36
}
37
38
myJsonString = (new JavaScriptSerializer()).Serialize(myList);
39
return myJsonString;
40
41
}
42
}
43
AND MY EVENTS CLASS
JavaScript
1
18
18
1
public class Events
2
{
3
public int id { get; set; }
4
public String title { get; set; }
5
public String start { get; set; }
6
public String end { get; set; }
7
8
public Events(int id2, String I, String t, String ds)
9
{
10
this.id = id2;
11
this.title = I;
12
this.start = t;
13
this.end = ds;
14
}
15
16
17
}
18
HERE IS THE OUTPUT 😀 😀