json feed events: only calling controller when controller has no arguments - c#

I am trying to implement json feeds FullCalendar.
If I use a signature for GetCalendarEvents with no arguments, the View calls the function. If I use it with the start and end arguments, the function does not get called. The only thing different that I can find in my code appreciable to the code in the sample is that they somehow get away with calling the script in the view without the header information I have to put in.
Header Code in View
<link rel='stylesheet' href='~/Content/fullcalendar.css' />
<link rel='stylesheet' href='~/Content/scheduler.css' />
<script src='~/Scripts/jquery-2.2.0.js'></script>
<script src='~/Scripts/moment.min.js'></script>
<script src='~/Scripts/fullcalendar.js'></script>
<script src='~/Scripts/moment.js'></script>
<script src='~/Scripts/scheduler.js'></script>
This works fine in example code I downloaded from here.
http://www.codeproject.com/Articles/638674/Full-calendar-A-complete-web-diary-system-for-jQue
The following is the code in question.
View Code
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'agendaDay',
editable: true,
allDaySlot: false,
selectable: true,
slotMinutes: 15,
events: '/Calendar/GetCalendarEvents/'
});
Controller Code
public JsonResult GetCalendarEvents(double start, double end)
//public JsonResult GetCalendarEvents()
{
var fromDate = CalendarEvent.ConvertFromUnixTimestamp(start);
var toDate = CalendarEvent.ConvertFromUnixTimestamp(end);
var rslt = _orderService.Query(s => s.FromDate >= fromDate && s.ToDate <= toDate);
List<CalendarEvent> result = new List<CalendarEvent>();
CalendarEvent rec = new CalendarEvent();
rec.ID = "lskfj1231";
rec.title = "Testing";
rec.start = "2016-01-17T12:00:00Z";
rec.end = "2016-01-17T13:00:00Z";
result.Add(rec);
var eventList = from e in result
select new
{
id = e.ID,
title = e.title,
start = e.start,
end = e.end
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}

I sorted it out. For reasons unknown (I will look into this at some point and update this solution) the sample project/solution sends a request to the controller for start and end arguments in unix time format. My project/solution sends the request to the controller for start and end arguments in DateTime format.
I just modified my signature in the Calendar controller for GetCalendarEvents(DateTime start, DateTime end) and everything is great.
Thanks!

$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
data : {start : 11, end : 15}
defaultView: 'agendaDay',
editable: true,
allDaySlot: false,
selectable: true,
slotMinutes: 15,
events: '/Calendar/GetCalendarEvents/'
});
You need to pass attributes in the data parameter

You can use it by two ways.
1) Event as a json feed
eventSources: [
// your event source
{
url: '/Calendar/GetCalendarEvents/',
type: 'GET',
data: {
start: startDate,
end: endDate
},
error: function() {
alert('there was an error while fetching events!');
}
}
]
2) Event as a function
events: function(start, end, timezone, callback) {
$.ajax({
url: '/Calendar/GetCalendarEvents/',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function(events) {
callback(events);
}
});
}

In the example code that you downloaded this is handled in the fullcalendar.js file. Take a look the _fetchEventSource method() at line 984.
I think that this is where the dates are added into the controller method call. You could trace your code to see if it is running through the js file, but my guess is that you don't have this file included in the correct order so it isn't utilizing the methods in the fullcalendar.js file.

Related

JTable Not Showing Sort Or Pagination

I am passing in a JSON array to my JTable and am trying to use AJAX to show the data with no page load. This is an asp.net core mvc app with a C# back-end. The data loads, but as i said i do not have the ability to sort and all results are shown instead of only 10 per page as I request in the sorting param.
What do I ned to change here?
[Route("api/ca")]
public JsonResult Index()
{
var ListData = _context.CIModel.FromSql("StoredProcedureName").ToList();
return Json(new { Result = "OK", Records = ListData, TotalRecordCount = ListData.Count });
}
$('#btnTest').click(function () {
$('#jTableTest').jtable({
paging: true,
pageSize: '10',
sorting: true,
defaultSorting: 'Name ASC',
actions: {
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: 'https://localhost:44328/api/ca?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
type: 'GET',
dataType: 'json',
success: function (data) {
$dfd.resolve({ Records: data.records, Result: data.result, TotalRecordCount: data.TotalRecordCount });
},
error: function () {
$dfd.reject();
}
});
});
}
},
fields: {
name: {
title: 'Name',
width: '35%'
},
phone: {
title: 'Phone',
width: '15%'
},
yrsexp: {
title: 'Experience',
width: '15%'
}
}
});
$('#jTableTest').jtable('load');
});
Sorting and paging are both SERVER side operations. You need slight changes on both client and server.
On the client, in this example you don't need to write your own deferred function, Just give jTable the URL. It will then pass, paging (jtStartIndex and jtPageSize) and sorting (jtSorting) parameters to the server. These parameters are in the jtParams argument passed to the deferred function, so you have to forward them in you ajax call.
One the server, you need to respond to these sorting and paging parameters. Do note, that on a paged reply, TotalRecordCount is the total number of unpaged records. not the number returned. It is used by jTable to show the total number of pages.

Full Calendar button click not working

My full Calendar show data correctly using ajax . so i want to change the data on previous button click. But the button click function not working and how can i pass the data as parameter on previous and next button click
<script src="../assets/global/plugins/fullcalendar/lib/moment.min.js"></script>
<script src="../assets/global/plugins/fullcalendar/lib/jquery.min.js"></script>
<script src="../assets/global/plugins/fullcalendar/fullcalendar.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "attendance-full.aspx/GetEvents",
dataType: "json",
success: function (data) {
$('div[id*=calendar1]').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: $.map(data.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.title = item.EventName;
return event;
}), eventRender: function (event, eventElement) {
if (event.ImageType) {
if (eventElement.find('span.fc-event-time').length) {
eventElement.find('span.fc-event-time').before($(GetImage(event.ImageType)));
} else {
eventElement.find('span.fc-event-title').before($(GetImage(event.ImageType)));
}
}
},
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
$('div[id*=calendar1]').show();
//below code not working
$(".fc-prev-button span").click(function () {
alert("Hai");
})
});
My console is error free .
$(".fc-prev-button span").click(function () { runs before your calendar is created (because you wait to create the calendar until ajax has run, and ajax is asynchronous). Therefore there is no button for your code to bind the event to.
Simply move
$(".fc-prev-button span").click(function () {
alert("Hai");
});
to the end of your ajax "success" function.
N.B. I would also suggest that you re-consider how you're getting your events. Currently you fetch all events into the calendar, and the calendar cannot be displayed until the events are fetched. If your application is live for a long time, and builds up a lot of historical events, consider what will happen after a few years when there is a long list of events - it will take a long time to load them all, with no calendar on screen, and unless your situation is unusual, then probably no-one will look at anything from a long time ago, so it's a waste of time to load them.
FullCalendar is actually designed to work in a way that fetches only the events that are needed for the view and date range currently being displayed. So you fetch the minimum required events. If the user changes the view or date to something else, fullCalendar requests more events from the server, and sends it the date range required. This is usually much more efficient.
In your case you could re-write it something like this snippet below. Bear in mind you'd also have to change your GetEvents server method so that it filters the list of events by the dates supplied. I can't see that code so I can't advise exactly what you would need to do, but hopefully it will be fairly simple to add a couple of extra parameters and add a clause to your database query to compare the dates.
$(document).ready(function() {
$('div[id*=calendar1]').show();
$('div[id*=calendar1]').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: function(start, end, timezone, callback) {
$.ajax({
type: "POST",
contentType: "application/json",
data: '{ "start": "' + start.format("YYYY-MM-DD") + ', "end": ' + end.format("YYYY-MM-DD") + '}',
url: "attendance-full.aspx/GetEvents",
dataType: "json",
success: function(data) {
var events = $.map(data.d, function(item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.title = item.EventName;
return event;
});
callback(events);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
},
eventRender: function(event, eventElement) {
if (event.ImageType) {
if (eventElement.find('span.fc-event-time').length) {
eventElement.find('span.fc-event-time').before($(GetImage(event.ImageType)));
} else {
eventElement.find('span.fc-event-title').before($(GetImage(event.ImageType)));
}
}
},
});
$(".fc-prev-button span").click(function() {
alert("Hai");
});
});
See https://fullcalendar.io/docs/event_data/events_function/ for more details of the event feed function.

Json data in fullcalendar

Using a javascript plugin Fullcalendar, and I'm trying to load data into the events handle in the javascript plugin. The data is being processed but isn't being displayed in the calendar.
If I was to guess the issue, I think it would have to do with my date format being returned, to the full calendar plugin. Is it supposed to be returned in unixtimestamp? Here is the Json result.
They're valid unixtimestamps.
Here is my controller.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult CalendarData()
{
DateTime start = new DateTime(1970, 1, 1);
DateTime end = new DateTime(1970, 1, 1);
start = start.AddSeconds(double.Parse(Request["start"]));
end = end.AddSeconds(double.Parse(Request["end"]));
// call middle tier/orm/whatever to get data from source
List<webby.Models.Calendar> list = SearchForEvents(start, end);
return Json(list, JsonRequestBehavior.AllowGet);
}
private List<webby.Models.Calendar> SearchForEvents(DateTime start, DateTime end)
{
var eventList = (from e in db.Calendars
select new
{
ID = e.ID,
title = e.title,
start = start,
end = end
}).AsEnumerable().Select(x=> new webby.Models.Calendar{ID=x.ID, title =x.title, start = x.start, end =x.end}).ToList();
return (eventList);
}
And my fullcalendar plugin:
<script>
$(document).ready(function () {
$('#calendar').fullCalendar({
height: 170,
selectable: true,
editable: true,
defaultView: 'basicWeek',
events: "/Home/CalendarData",
dayClick: function (date, jsEvent, view) {
$.ajax(
{
url: '#Url.Action("Index","Home")',
type: "POST",
data: JSON.stringify({ date: date }),
contentType: "application/json; charset=utf-8",
cache: false
}).success(function (response) {
$("#modalLoad").html(response);
$("#myModal").modal();
}).error(function (a,b,c) {
alert(a.responseText);
alert(b);
alert(c);
});
}
});
});
</script>
I'm not certain that you can use UNIX timestamps here. I think it has to be something moment() can parse. See http://momentjs.com/docs/#/parsing/

Accessing C# variable from Javascript in asp.net mvc application

I have a problem in How to use javascript variables in C# and vise versa : I have this Model passing to the view:
public List<Tache> Get_List_Tache()
{
Equipe _equipe = new Equipe();
List<Tache> liste_initiale = _equipe.Get_List_tache();
return liste_initiale;
}
It's a list of objects Tache in which I'd like to use it's three fields Tache_description, Begin_date and End_date.
In my JavaScript code I have this function and it works fine:
<script>
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
editable: true,
events: [
#foreach (var m in Model.Get_List_Tache())
{
#:{title : #m.Tache_description , start: #m.Begin_date , end : #m.Begin_date }
}
]
});
});
</script>
The values of the array events are just for test, and I need to fill events by the value of the Model. For each element like this: title = Tache_description, start = Begin_date and end = End_date.
So how can I do this task? Any suggestions?
Try this,
foreach (var item in YourList)
{
events: [{ title: '#item.title', start: '#item.start', end: '#item.end'}]
}
So, in this code just replace name your model entity.
Make a foreach razor loop within javascript :
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
editable: true,
events: [
#
{
bool isFirst = true;
}
#foreach(var m in Model)
{
if(!isFirst)
{
#:,
}
#:{title: #m.Tache_description, ...<other properties here>}
isFirst = false;
}
]
});
For title, you can do title = "#Tache_description"
Not sure about the format/type of your Begin_date and End_date, you may need some function to read the date into a javascript format. Shouldnt be that hard.
Loop through each element and add the elements to the events array. It is something like...
events = new Array()
#foreach(tache in list){
item = { blah : blah, blah : blah };
events.push(item);
}
for each c# item in this c# list, write these lines of javascript. You may end up with a very long javascript code block, but it should do the trick. Above is pseudocode.
To add to Darin's answer: If you need the server-side variables in an external JavaScript file, take a look this blog post: Generating External JavaScript Files Using Partial Razor Views
1: if your model is expecting the list of Tache then you have the whole list you can manipulate.
2: you can get the data using jquery ajax as json data by calling your action Get_List_Tache().
Assuming this javascript is inline in your page you could do the following:
#model IList<Tache>
<script type="text/javascript">
var events = #Html.Raw(Json.Encode(Model.Select(x => new { title = x.Description, start = x.Begin.ToString("o"), end = x.End.ToString("o") })));
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: events
});
</script>
This example assumes that your Tache model has properties Description, Begin and End:
public class Tache
{
public string Description { get; set; }
public DateTime Begin { get; set; }
public DateTime End { get; set; }
}
And if this script is in a separate javascript file you could still set a global events variable in your view which will later be used by your script. Alternatively you could fetch this model using an AJAX call.

How to edit event which was saved ealier from full calender in MVC 4?

I am using Full Calender in my application and want to edit the events which was saved earlier.
How can I edit the events? My code is as shown below.
I am using SQL as a database. Just want to edit the event which are displyed in the full calender.
#{
ViewBag.Title = "schedule";
}
#Html.Partial("_Calendar")
<script type="text/javascript">
$(function () {
var date = new Date();
var d = date.getDate();
var y = date.getFullYear();
var m = date.getMonth();
var calendar = $('#calendar').fullCalendar({
header: { left: 'prev,next today', center: 'title' },
selectable: true,
theme: true,
minTime: '8:00',
defaultEventMinutes: 30,
maxTime: '17:00',
allDaySlot: false,
defaultView: 'agendaWeek',
weekends: false,
firstHour: 9,
selectHelper: true,
select: function (start, end, allDay) {
//var date1 = dateFormat(new Date(start).toGMTString(), 'mm/dd/yyyy HH:MM:ss');
//var date2 = dateFormat(new Date(end).toGMTString(), 'mm/dd/yyyy HH:MM:ss');
var title = prompt('Event Title:');
if (!!title) {
$.ajax({
type: "POST",
data: { Start: start.toJSON(), End: end.toJSON(), Note: title },
url: rootURL + "Contractor/schedule/SaveSchedule",
color:'yellow',
dataType: "json",
success: function (data) {
$('#eventToAdd').modal('hide');
calendar.fullCalendar('renderEvent', { title: title, start: start, end: end, allDay: allDay }, true);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#eventToAdd").dialog("close");
}
});
}
calendar.fullCalendar('unselect');
},
eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc, calEvent, jsEvent, ui, view) {
var date1 = dateFormat(new Date(event.start), 'mm/dd/yyyy HH:MM:ss');
var date2 = dateFormat(new Date(event.end), 'mm/dd/yyyy HH:MM:ss');
$.ajax({
type: "POST",
data: { 'id':event.id, 'Start': date1, 'End': date2},
url: "/Contractor/schedule/UpdateSchedule",
dataType: "json",
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
},
editable: true,
events: '#Url.Action("Getevent","Schedule")',
eventColor: '#028323'
});
});
</script>
you could implement following method:
eventRender: function(event, element, view) {}
This function is written in the same way as eventDrop.
The parameter element is the div that forms the event, you can add an onclick event to this or append some html to its contents with a button. That way you can show your popup or navigate to an edit page. You can use something like firebug to inspect and adjust the html and see what is possible.
For more detailed information, you can check http://arshaw.com/fullcalendar/docs/event_rendering/eventRender/
There you can add an onclick handler or maybe an image with an onclick handler. In the onclick you can show a popup of some sort or navigate to an other page. In the popup or the other page you can make a form to edit your event. When the edit is complete reload the events or navigate back to your calendar and you will see the updated event.

Categories

Resources