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>"
Related
I am pulling an XML template from the database and then using this template in my view (DYMO labels).
My issue is that when I use #Html.Raw, even with quotes around it, it only reads the first line as "Text" and after the line break reads the rest of the XML file as code on the page.
Picture below:
1
The first line appears fine, but starting with <DesktopLabel Version the XML is rendered as not plain text inside quotes.
Here is my current behind the scenes code:
var labelXml = '#Html.Raw(Model.XML)';
I need the entirety of the string stored in quotes ("", ''). Any help?
you need to encode the xml
#Html.Raw(Html.Encode(Model.XML))
I was able to resolve this issue using a JSON AJAX controller action call. Code and explanation below in case anyone ever needs help on this:
try {
var _size = "#Model.size";
$.ajax({
data: { size: _size},
type: "POST",
url: "/Unit/GetXMLFile/",
success: function (data) {
var labelD = dymo.label.framework.openLabelXml(data);
labelD.print(printerName);
},
error: function (response) {
alert("error" + response.responseText);
}
});
}
catch(err) {
alert("Couldn't load label");
return;
}
Because we are directly injecting the XML string into our DYMO framework we prevent any chance of encoding the <> characters as < and >.
I believe that the root issue came from attempting to transfer XML strings from Viewmodel > Javascript. Even attempting to store the XML in the viewmodel and store as plain text once inside the view did not work.
The only method that worked was the AJAX direct controller action that keeps XMLs format without any conversion.
Here is my controller action:
[HttpPost]
public JsonResult GetXMLFile(string size)
{
string XML = "";
if (size == "Small")
{
XML = db.UnitLabels.Where(x => x.Size == "Small").Select(x => x.LabelXML).FirstOrDefault();
}
else
{
XML = db.UnitLabels.Where(x => x.Size == "Large").Select(x => x.LabelXML).FirstOrDefault();
}
return Json(XML, JsonRequestBehavior.AllowGet);
}
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/
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));
}
});
EDIT: I've gotten the "famous question" badge with this question, so I figured I'd come back to it and stick what happened to me right at the very tippy top for people searching it to get an answer right away.
Basically, I was new to JSON. JSON is an object (obviously), as it contains all kinds of stuff! So I was like "Hey, javascript, just pop up an alert with all of this JSON data", expecting it to give me the JSON data as a string. But javascript doesn't do that (which is good!), so it was like "Hey, this is how we display objects, [object Object]".
What I could've done is something like alert(obj.DATA[0][1]) and it would've shown me that bit of the object.
What I really wanted was to verify that I was making good JSON data, which I could've checked with JSON.stringify.
Anyway, back to our regularly scheduled questions!
I'm trying to get some JSON data with an ajax call, but jQuery doesn't seem to like my JSON.
if I do something like:
function init2() {
alert("inside init2");
jQuery.ajax({
url: "/Mobile_ReportingChain.cfm",
type: "POST",
async: false,
success: function (data) {
alert(data);
var obj = jQuery.parseJSON(data);
alert(obj);
}
});
}
I get this as from alert(data):
{"COLUMNS":["MFIRST_NAME","MLAST_NAME","MMDDL_NAME","MEMPLY_ID","MAIM_NBR","EMPLY_ID"],
"DATA":[
["FNAME1 ","LNAME1 ","MI1 ","000-14-7189","026-0010","000-62-7276"]
,["FNAME2 ","LNAME2 ","MI2 ","000-01-2302","101-1850","000-14-7189"]
,["FNAME3 ","LNAME3 ","MI3 ","000-91-3619","102-1000","000-01-2302"]
,["FNAME4 ","LNAME4 ","MI4 ","000-25-9687","102-1000","000-91-3619"]
]}
which JSONLint says is valid json. alert(obj) gives me this, however:
[object Object]
adding dataType: "json" or "text json" just makes it report [object Object] at alert(data).
I'd really like to get this figured out, does anyone know why it's doing this? I'm pretty new at jQuery, my goal is to get an array for each of the columns. The same code I'm using has worked on a different page it looks like, which is what's bothering me the most.
The alert() function can only display a string of text. As its only parameter it takes a string or an object. The object will however be converted into a string that can be displayed.
When fetching JSON through jQuery, the $.ajax() method will automatically parse the JSON and turn it into a JavaScript object for you. Your data variable is therefor a JavaScript object, and not a JSON string as one might expect.
Since alert() only can display strings, when trying to alert your data object, your object will be turned into its string representation. The string representation of a JavaScript object is [object Object].
For debug-purposes you can use console.log(data) instead. You can then inspect the object and its content through the console in your browsers developer tools.
function init2() {
jQuery.ajax({
url: "/Mobile_ReportingChain.cfm",
type: "POST",
dataType: "json",
async: false,
success: function (data) {
console.log(data);
}
});
}
If you for some reason still want to alert the JSON-data, then you would have to turn your data object back into a JSON-string. To do that you can make use of JSON.stringify:
alert(JSON.stringify(data));
it wants a string
var obj = $.parseJSON(JSON.stringify(data));
try sending that object to console.log. You'll get a clearer picture what does it contain.
Also, put dataType: 'json' and remove parseJSON because it's all the same.
This is how it's supposed to work. Your JSON becomes a javascript object. You can then manipulate that object as a regular javascript object.
data.COLUMNS for instance should return an array.
[object Object] is the string representation of a javascript object.
Try accessing properties of the object.
alert(data.COLUMNS[0]);
jQuery.parseJSON will convert the json string into json object so alert(obj) will show you [object Object] since it is an object.
If you want to see what obj contains then use console.log(obj) and then check console log message.
$.getJSON( "UI/entidades.json.php", function(data){
result = JSON.stringify(data);
alert(result)
console.log(result)
})
(I knows this is an jquery problem; but just bear with me for a min. so that i can explain why this problem occurred to me in the first place).
I wanted to fill in the gaps made my deletion of records in my MySQL table ( primary key that was auto increment. So when records where deleted in between my id had missing keys. I though some mechanism to show those missing keys. So i created the code that created an array through a loop then deleted those keys that were present and echo backed that array (of course json_encode that array).
But to my amazement what ever I did it always end up giving me [object Object].
It baffled me a lot that were was the problem.
Solution: Just realigning the array and all my problem gone.
Below I would give an simplified example.
<!DOCTYPE html>
<html>
<head>
<script src="../js/jquery/jquery3.x/jquery-3.3.1.min.js"></script>
<title></title>
<script type="text/javascript">
$(function () {
$('#generate').click(function () {
$.get('tmp2.php?tab=1', function (data) {
var retStr = '<table>';
var par = $.parseJSON(data);
$(par).each(function () {
retStr += '<tr><td>' + this + '</td></tr>';
});
retStr += '</table>';
$('#res').html(retStr);
});
});
});
</script>
</head>
<body>
<input type="button" value="generate" id="generate" />
<div id="res"></div>
</body>
</html>
And the controller
<?php
if (!empty($_GET['tab'])) {
$ids = array();
for ($i = 0; $i < 50; $i++)
$ids[] = $i;
for ($i = 0; $i < 50; $i = $i + 2)
unset($ids[$i]);
// echo json_encode($ids); // this will generate [object Object]
$res = array();
foreach ($ids as $key => $value) {
$res[] = $value;
}
echo json_encode($res);
exit();
}
?>
Whats wrong in below JSON Object definition
I am trying to create a new JSON Object like below.
So that my idea is to access COMPANYSETUP.HourSetup.initiate();
Not sure the error ?
COMPANYSETUP = {
initiated : false,
companyId : "",
initiate : function() {
if(!initiated){
// TO DO
initiated = true;
} },
HourSetup = {
initiated : false,
hourId : "",
initiate : function() {
if(!initiated){
// TO DO
initiated = true;
}
}
}
};
Assuming you want a javascript object and not JSON, which disallows functions,
HourSetup =
Should be changed to:
HourSetup :
Also, as JonoW points out, your single line comments are including some of your code as the code is formatted in the post.
There's a "=" that shouldn't be there. Change it to ":"
JSON is a form of JavaScript deliberately restricted for safety. It cannot include dangerous code elements like function expressions.
It should work OK in plain eval()ed JavaScript, but it's not JSON.