Json data in fullcalendar - c#

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/

Related

passing date to controller using ajax in mvc

I want to update my chart according to user date selection. here i am using chart js. So i want to pass from date and to date value using Ajax to controller so that i can do data filters. But the problem is that the dates are not submitted to controller action.Please guide me where i have missed.
i have tried many links too but is not helping me.
Post datetime to controller
this is also not helping.
Here is my Script
<script>
function SendDates() {
var ListOfDates = [];
ListOfDates.push($("#fromDate").val());
ListOfDates.push($("#endDate").val());
dates = JSON.stringify({ 'ListOfDates': ListOfDates });
alert(dates)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: "/dashboard/sendDates",
data: dates ,
success: function (data) {
if (data.status == "successfull") {
alert("Dates were sent successfully ");
} else {
alert("Dates werenot sent successfully ");
}
},
error: function (error) {
console.log(error);
}
})
}
</script>
and this is controller
[HttpPost]
public JsonResult sendDates(DateTime receivedDates) {
DateTime dates = receivedDates;
Debug.WriteLine(" Date is:"+ dates );
return new JsonResult { Data = new { status = "successfull" }
};
}
when i change the data type DateTime to String in controller i get success message but seeing debug output there there is blank.
[HttpPost]
public JsonResult sendDates(String receivedDates) {
var dates = receivedDates;
Debug.WriteLine(" Date is:"+ dates );
return new JsonResult { Data = new { status = "successfull" } };
}

Why is this value zero after ajax call finishes (asp.net mvc 3 and jQuery)?

Here is my ajax call:
var totalCost = 0;
function GetTotalCost(start, end, rID)
{
$.ajax({
url: '#Url.Action("CalculateTotalcost")',
type: 'POST',
data: JSON.stringify({ start:start, end:end, rID:rID}),
dataType: 'json',
processdata: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { totalCost = data; }
// error: function (xhr, ajaxOptions, thrownError) { $('.datepicker1').datepicker("hide"); },
// complete: function (x, y) { $('.datepicker1').datepicker("refresh"); }
});
}
Here is my function from which I call ajax:
$('.datepicker2').datepicker({
dateFormat: 'dd/mm/yy',
firstDay: 1,
yearRange: '2012:2100',
beforeShowDay: function (date) {
var day = date.getDate();
if (day in alreadyTakenDays) {
return [false, '', alreadyTakenDays[day]];
}
else return [true, 'IsActive'];
},
onChangeMonthYear: function (year, month, inst) {
alreadyTakenDays = {};
getEvents(month, year);
},
onSelect: function (dateText, inst) {
var end = dateText.substring(0, 2);
console.log(end);
var rID = $('#RoomID').val();
console.log(rID);
var startingHole = $('#DateOne').val();
var start = startingHole.substring(0, 2);
console.log(start);
GetTotalCost(start, end, rID);
document.getElementById('TotalCost').value = totalCost.toFixed(2);
}
});
After jQuery script is executed I always get 0 for totalCount?
Why is this happening? What should I Do?
I would like to appoint totalCount to Html.TextBoxFor in ASP.NET MVC 3, that is why I need totalCount. Please help.
The ajax call is asychronous and hasn't completed when you set the value on your 'TotalCost' text box.
You should have success function handler like this to get correct total cost value:
function GetTotalCost(start, end, rID)
{
$.ajax({
url: '#Url.Action("CalculateTotalcost")',
type: 'POST',
data: JSON.stringify({ start:start, end:end, rID:rID}),
dataType: 'json',
processdata: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { totalCost = data;
document.getElementById('TotalCost').value = totalCost.toFixed(2);
}
});
}
In code like this:
GetTotalCost(start, end, rID);
document.getElementById('TotalCost').value = totalCost.toFixed(2);
First line cause ajax call, but it does not wait for response and second line is executed immediately. Later, after server responded, success callback function is executed. And it will be executed after second line. That is why your total value is wrong - correct value is set to totalCost after you update TotalCost input.
Because your post is asynchronous and you are trying to set a js variable that is global to the page. Create a function that sets the variable and call it from the call back, then you will see the result.
That is because of Asynchronous ajax Request..
By the time you the event is handled , the request has not been completed yet.
Welcome to the wonderful world of AJAX.

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.

Ajax function doesn't seem working

I'm developing an online application of tennis club management... (MVC 3, Entity Framework Code first,...)
I've an Interface that allows the user to consult the available tennis court :
In my "AvailableCourtController", I've a function which return the tennis courts :
[HttpPost]
public JsonResult GetTennisCourt(DateTime date)
{
var reservations = db.Reservations.Include(c => c.Customer);
foreach (var reservation in reservations)
{
//Verify that a court is available or not
if (reservation.Date ==date)
{
if (date.Hour > reservation.FinishTime.Hour || date.Hour < reservation.StartTime.Hour)
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(t => t.ID == id);
tennisCourt.Available = true;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
}
else
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(s => s.ID == id);
tennisCourt.Available = false;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
break;
}
}
}
var courts = from c in db.TennisCourts
select c;
courts = courts.OrderBy(c => c.ID);
return Json(courts, JsonRequestBehavior.AllowGet );
}
So, I would like to change the color of my label if the tennis court is busy or free... For that I use "Ajax":
"View" (What I've tried to make)
<input id="datePicker" type= "text" onchange="loadCourts"/>
<script type="text/javascript">
$('#datePicker').datetimepicker();
</script>
<script type="text/javascript">
function loadCourts() {
var myDate = $('#datePicker').value();
$.ajax({
url: ("/AvailableCourt/GetTennisCourt?date=myDate "),
success: function (data) {
alert('test');
//change label's color
}
});
}
</script>
I never get the message "test"... So I have make something wrong with my Ajax function or my controller's method... My goal is to get the tennis court, check if they're free or not and change color in red if busy, and in green if free...
Can you help me to find what I'm doing wrong please? Sorry :( But I'm a beginner with Ajax...
This line is not passing a date in the querystring:
url: ("/AvailableCourt/GetTennisCourt?date=myDate "),
should be:
url: ("/AvailableCourt/GetTennisCourt?date=" + myDate),
EDIT: Also you're not getting the value correctly:
var myDate = $('#datePicker').value();
should be:
var myDate = $('#datePicker').val();
Your datetimepicker() call has to occur inside of a document.ready. Here is the corrected code:
<input id="datePicker" type= "text"/>
<script type="text/javascript">
$(document).ready(function () {
$('#datePicker').datetimepicker();
$('#datePicker').change(loadCourts);
});
function loadCourts() {
var myDate = $('#datePicker').val();
$.post({
data: "{ 'date' : " + myDate + " }",
url: (#Url.Action("AvailableCourt", "GetTennisCourt"),
success: function (data) {
alert('test');
//change label's color
}
});
}
</script>
}
Your url is wrong :-)
Should be:
$.ajax({
url: "/AvailableCourt/GetTennisCourt?date="+myDate, // without ( )
success: function (data) {
alert('test');
//change label's color
}
});
A more verbose AJAX call:
$.ajax({
type: 'POST',
data: "{ 'date' : " + myDate + " }",
url: '/AvailableCourt/GetTennisCourt',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000, // 8 second timeout
success: function (msg) {
},
error: function (x, t, m) {
if (t === "timeout") {
HandleTimeout();
} else {
alert(t);
}
}
});
I agree with #CAbbott that your URL was not created correctly. But with date values (and multiple query string values in general), you may be better off adding your date parameter in a data object literal in your ajax call:
function loadCourts() {
var myDate = $('#datePicker').val();
$.ajax({
url: ("/AvailableCourt/GetTennisCourt"),
data: { date: myDate },
success: function (data) {
alert('test');
//change label's color
}
});
}
jQuery will append your data onto the querystring for you and format it appropriately.
From the jQuery API docs:
The data option can contain either a query string of the form
key1=value1&key2=value2, or a map of the form {key1: 'value1', key2:
'value2'}. If the latter form is used, the data is converted into a
query string using jQuery.param() before it is sent.

How countdown get Synchronise with jquery using "jquery.countdown.js" plugin?

Unable to get the correct Ans as i am getting correct result from the Jquery variable "shortly" but when i am Synchronise with function "serverSync" all will set to 0:0:0 i have checked both having a same date.
ref. site
http://keith-wood.name/countdown.html
here is my code
[WebMethod]
public static String GetTime()
{
DateTime dt = new DateTime();
dt = Convert.ToDateTime("April 9, 2010 22:38:10");
return dt.ToString("dddd, dd MMMM yyyy HH:mm:ss");
}
html file
<script type="text/javascript" src="Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript" src="Scripts/jquery.countdown.js"></script>
<script type="text/javascript">
$(function() {
var shortly = new Date('April 9, 2010 22:38:10');
var newTime = new Date('April 9, 2010 22:38:10');
//for loop divid
///
$('#defaultCountdown').countdown({
until: shortly, onExpiry: liftOff, onTick: watchCountdown, serverSync: serverTime
});
$('#div1').countdown({ until: newTime });
});
function serverTime() {
var time = null;
$.ajax({
type: "POST",
//Page Name (in which the method should be called) and method name
url: "Default.aspx/GetTime",
// If you want to pass parameter or data to server side function you can try line
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
async: false,
//else If you don't want to pass any value to server side function leave the data to blank line below
//data: "{}",
success: function(msg) {
//Got the response from server and render to the client
time = new Date(msg.d);
alert(time);
},
error: function(msg) {
time = new Date();
alert('1');
}
});
return time;
}
function watchCountdown() { }
function liftOff() { }
</script>
You're setting the server time equal to the time you're counting down towards.
Since the new "serverSync" time and the "until" time are the same, the countdown will just be 0's across the board.

Categories

Resources