I am using fullCalendar in my MVC project. I downloaded fullCalendar from Nuget but it doesn't display my data on the calendar. I can get my data but it is not displaying.
What is going wrong in my code?
MVC action method:
public JsonResult GetEvents()
{
dbContext = new Context();
var events = dbContext.Schedule.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
View:
I think the GenerateCalendar function is not working.
<link href="~/Content/fullcalendar.min.css" rel="stylesheet" />
<script src="~/Content/PanelJS/jquery.min.js"></script>
<script src="~/Content/PanelJS/moment.min.js"></script>
<script src="~/Scripts/fullcalendar.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url:"#Url.Action("GetEvents","Schedule")",
success: function (data) {
$.each(data,function(i,v)
{
events.push({
title: v.Name,
start: v.Date,
end: v.EndDate,
location:v.Location
});
console.log(events);
})
GenerateCalendar(events);
},
error:function(error)
{
alert('Error');
}
});
function GenerateCalendar(events)
{
$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar(
{
contentHeight: 400,
defaultDate: new Date(),
color:'lightBlue',
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right:'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events:events
})
}
});
</script>
Console result ;
end: "10/05/2018 "location: "Chicago" start: "09/05/2018" title: "MyEvent"
From the console output it looks like your dates are being supplied as strings in an ambiguous format. fullCalendar / momentJS will not understand that without being explicitly told what you format is being used. It could be dd/mm/yyyy or mm/dd/yyyy. There is no way for the parser to know what to do with it.
Therefore fullCalendar will not be able to use this data as an event, because it doesn't understand the start and end dates.
The date and time formats accepted by fullCalendar are the same as those accepted by momentJS (since it uses momentJS to work with dates). This is documented here: https://fullcalendar.io/docs/moment and in more detail here: http://momentjs.com/docs/#/parsing/
Therefor, you can either
1) (recommended) Re-write your server-side code so that it returns dates in ISO format. Generally if you are using DateTime objects in your C# code, then the .NET JSON serialiser will do that for you automatically. Since you're directly serialising the result of an Entity Framework query into JSON, then I would suspect that the Date and EndDate properties of your Schedule class are strings rather than DateTimes, which in turn means that you may be storing dates as strings within your database. If so, that is a bad practice which you should fix immediately by storing dates as datetime columns. Dates are not strings, they are dates. What you see on screen (e.g. 09/05/2018) is merely one of many possible representations of that date in a human-readable form. It is not a good format for actually storing the date information.
OR
2) (alternative) If that's not the case, or not possible for some reason, then tell momentJS to parse the dates according to the format you're supplying and then pass the data to fullCalendar as a moment object, e.g.
events.push({
title: v.Name,
start: moment(v.Date, "DD/MM/YYYY"),
end: moment(v.EndDate, "DD/MM/YYYY"),
location: v.Location
});
In-depth documentation of the format-specific parsing functionality in momentJS can be found here: http://momentjs.com/docs/#/parsing/string-format/
Related
I'm hoping that someone can please help with FullCalendar (v4) not loading events when using the Json option. It works fine when the same data is hard coded as an event.
The Json produced is valid - i.e. it validates with https://jsoncompare.com
I've spent an enormous amount of time trying to figure this out myself and I've hit a wall - so time to ask for help.
I've tried using the built in Net Json serializer - but this produces the wrong date format, so I've also tried newtonsoft Json.net, which does produce the correct date format for FullCallendar but still will not load events.
There are no JS console errors when using the JSON, it simply does not load into the calendar. The JSON is coming from the same domain (i.e. not affected by cross domain issue).
Any help/advice would be most welcome, thank you.
THIS WORKS PERFECTLY, WHEN THE EVENTS ARE HARDCODED:
var calendar = new FullCalendar.Calendar(calendarEl,
{
plugins: ['interaction', 'dayGrid', 'timeGrid'],
defaultDate: new Date(),
defaultView: 'timeGridWeek',
minTime: '07:00:00',
maxTime: '22:00:00',
timeZone: 'local',
header: {
left: 'prev,next today',
center: 'title',
right: 'timeGridDay,timeGridWeek,dayGridMonth'
},
events: [ //hardcoded events load just fine
{
id: '12',
title: 'Event Name',
start: '2019-08-28T08:00:00',
end: '2019-08-28T08:30:00'
}
]
});
calendar.render();
}
WHEN USING THE JSON OPTION, IT DOES NOT WORK:
//JSON provided events do not load
events: {
url:'/CourseTimetable/GetAllEventsAsJson'
}
ALTERNATIVE WAY OF PROVIDING FEED (without braces and "url:" prefix):
events:'/CourseTimetable/GetAllEventsAsJson'
THE URL WORKS FINE - validates as JSON - AND DOES NOT GENERATE ANY ERRORS - IT PRODUCES:
"[{\"id\":12,\"title\":\"Event 1\",\"start\":\"2019-08-29T08:00:00\",\"end\":\"2019-08-29T08:30:00\"}]"
HEADER and cors info:
Content-Type: application/json; charset=utf-8
Referer: http://localhost:54928/CourseTimetable
Request Method: GET
Status Code: 200 OK
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
Thanks in advance for any help/advice :)
Here are the two alternative controller versions (with standard .net and then with json.net)
Standard .net
public JsonResult GetAllEventsAsJson(DateTime? start = null, DateTime? end = null)
{
var events = db.CourseTimetables.Where(p => p.StartTime >= start && p.EndTime <= end)
.Select(s => new
{
id = s.Id,
title = s.Title,
start = s.StartTime,
end = s.EndTime
}).ToList();
//using built in .NET serialiser
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
OUTPUT FROM ABOVE ACTION (main difference being the outputted dates and escaping):
[{"id":12,"title":"Event 1","start":"\/Date(1567062000000)\/","end":"\/Date(1567063800000)\/"},{"id":13,"title":"Event 2","start":"\/Date(1567148400000)\/","end":"\/Date(1567150200000)\/"}]
Json.Net version
public ActionResult GetAllEventsAsJson(DateTime? start = null, DateTime? end = null)
{
var events = db.CourseTimetables.Where(p => p.StartTime >= start && p.EndTime <= end)
.Select(s => new
{
id = s.Id,
title = s.Title,
start = s.StartTime,
end = s.EndTime
}).ToList();
//USING JSON.NET
string jsonData = JsonConvert.SerializeObject(events);
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
OUTPUT FROM ABOVE ACTION (dates are in correct iso format with this):
"[{\"id\":12,\"title\":\"Event 1\",\"start\":\"2019-08-29T08:00:00\",\"end\":\"2019-08-29T08:30:00\"},{\"id\":13,\"title\":\"Event 2\",\"start\":\"2019-08-30T08:00:00\",\"end\":\"2019-08-30T08:30:00\"}]"
This format: "[{\"id\":12,\"title\":\"Event 1\",\"start\":\ ...etc is the problem. You're double-serialising the data. See those outer quote marks (") and slashes \? The outer quote marks indicate that you are returning a simple string as the response (which is valid JSON, but will be treated as plain text by the parser), and the slashes are the result of having to escape the quote marks within the string. Thus the inner data, while it looks like JSON, is not treated as JSON by the client-side parser. Instead the whole thing is just treated as one big string, with no objects, properties etc within it.
In ASP.NET MVC, return Json... expects you to supply it with an object. It will then automatically serialise that to JSON for you. You don't need to serialise it before you pass it in. Just remove that code and send events directly to the Json() method:
public ActionResult GetAllEventsAsJson(DateTime? start = null, DateTime? end = null)
{
var events = db.CourseTimetables.Where(p => p.StartTime >= start && p.EndTime <= end)
.Select(s => new
{
id = s.Id,
title = s.Title,
start = s.StartTime,
end = s.EndTime
}).ToList();
return Json(events, JsonRequestBehavior.AllowGet);
}
P.S. What version of MVC are you using? The more recent, supported versions use JSON.NET as the default serialiser anyway, so there should be no reason to have to do it manually. If you have an older version of MVC (which it looks like you might have since it's producing those odd date formats e.g. Date(1567062000000)\) and cannot upgrade for some reason, there are ways to make it use JSON.NET by default. Alternatively, you could do the serialisation yourself using JSON.NET, and then just return a plain string from your action method.
P.P.S. Another alternative to the above is to use the momentJS plugin in fullCalendar which then allows you to use momentJS to parse your dates - and momentJS includes the ability to parse ASP.NET's old date format.
When calling JsonRest using dojo, how can I pass parameters with it.
var rest = new JsonRest({
target: "/path/to/service"
});
JsonRest example:
require(["dojo/store/JsonRest"], function(JsonRest){
// create a store with target your service
var store = new JsonRest({
target: "/path/to/service"
});
// make a get request passing some options
store.query("foo=bar", {
start: 5,
count: 5,
sort: [
{ attribute: "color", descending: true }
]
}).then(function(results){
// result here
});
});
The function to use in your case is query with signature query(query, options)
When called, query will trigger a GET request to {target}?{query}, as described in dojo docs.
Please keep in mind that:
If query is an object, it will be serialized.
If query is a string, it is appended to the URL as-is.
If options includes a sort property, it will be serialized as a query parameter as well;
Your service/API should:
Return a array of objects in JSON format.
Return an empty array if no match is found.
res.json({data: new Date()});
This is the response: {data: '2014-05-20T01:40:34.993Z'}
How to configure express to return timestamp instead of date string?
{data: 1343235454545}
You need to use Date.now()
Example - res.json({data: Date.now()});
Then you will get result in timestamp "data": 1404359477253 likewise.
This worked out perfectly to filter all Date
app.set('json replacer', function (key, value) {
if (this[key] instanceof Date) {
// Your own custom date serialization
value = this[key].now();
}
return value;
});
You can use moment.js (as suggested by #swapnesh). But I found it more suitable to simply save the data as a timestamp. Since I'm using mongoDB I'm using Number for the data type.
So my schema looks something like this:
var myDataSchema = {
start: {type: Number, required: "myDataSchema.start is a required field"},
}
This will output:
{
"_id": "564c6828d4f028236cf1a6c8",
"start": 1450969200
}
`
Schema:({title:String},{timestamps:true})
`you can true the timestamps inside the model. I think problem solved
Good day! I need to render a model's attributes to JSON so I can pass them into a template.
Model:
var UserInfo = Backbone.Model.extend({
url: appConfig.baseURL + "users/",
});
Template:
<script type="text/html" class="template" id="profile-form">
<h2 class="ui-li-heading"><%= username %></h2>
<p class="ui-li-desc"><strong><%= phone %></strong></p>
</script>
View:
var ProfilePageView = Backbone.View.extend({
events: {
'click #edit': "edit"
},
initialize: function () {
this.template = $.tpl['profile-form'];
var user = new UserInfo()
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
console.log(user) //returns correct object with attrs
console.log(user.toJSON()) //returns empty object
},
render: function (eventName) {
$(this.el).html(this.template());
},
edit: function () {
window.workspace.navigate('#account/edit', { trigger: true});
}
});
When i put in console something like this, user.toJSON() returns correct data
var user = new UserInfo();
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
But when i put it to my view, its returns Object {}.
Where is a mistake or tell me how can differently pass to the template data received from the server in json format? Thanks!
You appear to have two problems. fetch is asyncronous, so you need to use a callback to use the information. But first, an explanation about toJSON. .toJSON() doesn't actually return a JSON string, it returns an object that is what you want JSON to stringify. This allows you to modify the toJSON method to customize what attributes will be taken from your model or collection and added to the JSON string representation of your model. Here is a quotation from the Backbone.js docs:
toJSON collection.toJSON([options])
Return a shallow copy of the model's attributes for JSON
stringification. This can be used for persistence, serialization, or
for augmentation before being sent to the server. The name of this
method is a bit confusing, as it doesn't actually return a JSON string
— but I'm afraid that it's the way that the JavaScript API for
JSON.stringify works.
So you should replace this line in your code
console.log(user.toJSON())
with this one
console.log(JSON.stringify(user))
The object that you saw was returned by toJSON will then be turned into JSON.
Now, even after you do that, it won't work properly, because you will execute the console.log before you get the data for your model from fetch. fetch is asynchronous, so you need to call any code you want to be executed after the fetch is done in the success callback:
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST',
success: function(){
console.log(user);
console.log(JSON.stringify(user));
}
});
I am using fullcalendar plugin -
//c#
public JsonResult Events(int start, int end) // GetEvents return an array of my DTO
{
return Json(GetEvents(ConvertFromUnixTimestamp(start), ConvertFromUnixTimestamp(end)), JsonRequestBehavior.AllowGet);
}
//html
<head>
<script type='text/javascript'>
$(document).ready(function () {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
month: 5,
year: 2011,
editable: false,
events: 'MyWebsite/Events'
});
});
</script>
The problem is the data is getting encoded, so I want to pass something like "<b>Name</b>" it gets encoded. So, I tried serializing with AllowHtml attribute but does not work also I have tried bunch of other things. What I need to do is somehow call serialize object without the encoding which I guess by default..or at least skip encoding for the one field with AllowHtml data annotation ? I have a looked at a similar problem.
Can anyone give me any help here I cannot really use Html.Raw() as I see it since I am passing the data to javascript I guess it just needs to be somehow decoded.
For doing this you will have to edit the fullcalendar.min.js or the fullcalendar.js file whichever that you have included and search for
"<span class='fc-event-title'>" + Ka(Q.title) + "</span></a>"
then add bold tags as follows
"<span class='fc-event-title'><b>" + Ka(Q.title) + "</b></span></a>"