.NET Core Object JSON Serialization to Javascript format - javascript

I've some problems with serializing my C# objects into a plain JSON string.
I user JsonConvert ( Newtonsoft's one) to format a model into a JSON. The problem is that that JSON string get's used in some Javascript, but the format is not good as in a quote gets written down as "&quote;" instead of "'". Any idea's on how to fix this ?
//...
#{
var dataJson = JsonConvert.SerializeObject(Model);
}
//...
<script>
function ChangeGroup(type) {
$.ajax({
url: //...,
data: #dataJson
});
}
</script>
what I get is this:
Some formatting options I forget to set ?

There's a much shorter, easier to use and remember in ASP.NET Core:
#Json.Serialize(Model);
When assigned to a JavaScript value, the resulting JavaScript is valid:
<script>
var model = #Json.Serialize(model);
</script>
With this, you don't have to worry about HTML-escaping the characters.

You can do this:
#{
var dataJson = new HtmlString(JsonConvert.SerializeObject(Model));
}
By default ASP.Net Core will HTML encode before rendering an # expression unless the expression evaluates to a type with the interface IHtmlContent (which HtmlString has). Another way is to write
#Html.Raw(dataJson)

I have used the following to get data out of my model into a JS object. Thought I would post to possibly help someone in the future...
var items = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Items));

Related

Passing a Django Object to Javascript

Below is the simplified version of my code
view.py:
context['colorObj'] = Colors.objects.all()
Now on template, I can just loop through {{colorObj}} to get the individual values inside the object.
However on JavaScript, this is not the case.
If I want to assign to a variable my colorObj, it just does not work(or maybe I am wrong).
Here is I first thought I should do:
JavaScript:
var colorObj = {{colorObj}};
the value of colorObj is still empty, and there are warning marks on the {{}}. Others suggested to use "" on the Javascript like var colorObj = "{{colorObj}}"; but JavaScript just treat this as a simple String.
Other suggestion is this:
from json import dumps
...
colorObj = Colors.objects.all()
context['colorObj'] = dumps(colorObj)
Then on JS:
var colorObj = {{colorObj| safe}};
But I got an error Object of type QuerySet is not JSON serializable pointing the error to the dumps line.
Note, I am using Django3.1.5
Though I asked about how to get the data from db to Javascript with this method, I proceeded to a different method since it matches my use case. I used #Mahdi Firouzjah's answer for this.
you could use ajax in templates and __ serialize in backend side.
then using javascript you're able to work with that object.

Assign a raw HTML tag to a JavaScript variable

I'm working on an existing ASP.Net application and came across an interesting piece of JavaScript that I've been wondering about.
A few variables are being declared as literals, and they aren't in strings. For example, something like this is done:
<script type="text/javascript">
var jsonData = <asp:Literal ID="MyJsonObject" runat="server" />;
......
</script>
And in the server side code(C#), these tags are actually being altered from a JsonTextWriter similarly to this:
var stringBuilder = new StringBuilder();
var stringWriter = new StringWriter(stringBuilder);
using (var jsonWriter = new JsonTextWriter(stringWriter))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("someProperty");
jsonWriter.WriteValue("someValue");
jsonWriter.WriteEndObject();
}
MyJsonObject.Value = stringBuilder.ToString();
This in turn is causing the jsonData variable to be able to be used as a Json object in the client side code.
What I've noticed is,
if I put single quotes around the tag and change it to:
<script type="text/javascript">
var jsonData = '<asp:Literal ID="MyJsonObject" runat="server" />';
......
</script>
This doesn't work as it's no longer coming across as a Json object, but as an actual string. However, as I would expect, when it's just a plain tag, I'm receiving several syntax errors from Visual Studio.
So my question is:
Is this something that's generally acceptable or should I avoid keeping things like this around? Yeah, it works, but it doesn't look right to me.
I've found a few different questions that seem to be related here, but none seem to provide any insight on my particular situation.
In short: Yes, this looks acceptable. That appears to be one of the intended use-cases of the <asp:Literal> tag. Since you're writing a Javascript object literal, you won't even need the single-quotes, since that will change how the code works.
The thing to note is that <asp:Literal> isn't an HTML tag, and therefore will not make it to the user as it is. The <asp:Literal> tag gets pre-processed by ASP.NET before the page is sent to the user (since you have runat="server" specified); therefore, it will be processed regardless of surrounding content and replaced entirely with the resolved string value. Thus, your rendered page will be transformed (on the server-side) from this:
var jsonData = <asp:Literal ID="MyJsonObject" runat="server" />;
to this:
var jsonData = {
"someProperty" : "someValue"
};
This is a good way of transferring rich data constructed on the server-side into the client-side Javascript without having to write out raw Javascript to the page.
If you wanted a JSON-formatted string instead, then doing what you're doing and calling JSON.stringify(jsonData) afterwards would be your best bet.

better way of passing URL string to javascript file?

I am using the following in my _layout.cshtml
<div id="authorLoader" data-request-url="#Url.Action("Index", "Author", new { area = "Book" })"></div>
In js file, I retrieve the url as so:
var url= $('#authorLoader').data('request-url');
Works fine, however, I end up having 20+ div tags in my layout page. Is there a better way to pass url strings to javascript? Or is this recommended way?
Thanks!
This is a decent way to do it.. I sometimes 'cheat' and drop in some JS right into my template, and do something like
<script>
var url = "#Url.Action("Index", "Author", new { area = "Book" })";
</script>
Its not much cleaner, but at least it saves a jquery operation.
Not sure of the context of this request, but could you construct a javascript array of URLs and then pass the array to the function that reads them? Or alternatively construct a JSON string. Depends on how you plan to use it.

Yet i'm finding difficult to understand JSON

hey guys, i have read This post, so what i got is JSON is the easiest way to translate a JavaScript object into a PHP/C# associative array or object (and vice-versa).
Now my question is what is goin' on in below code,i.e without JSON/XML i'm still can access my C# object in Javascript, may be i'm wrong, if so Please correct me:
C#
Foreach(DataRow dr in dvItems.Table.Rows) //dvItems is a DataView
{
strItems &= "'" & dr("ItemTitle") & "'," //strItems is a String
}
strItems = strItems.Trim(",")
Javascript : here i'm using Autocomplete.js using JQuery
function InitAutocomplete()
{
data = [<%=strItems %>].sort();
AutoComplete_Create('<%=txtItem.ClientId %>', data);
}
See i'm using strItems in javascript with servertag, so where exactly the JSON is used ? is .net doin' something internally ? i'm totally confused how JSON/XML is used to data passing ?
While you can pass data like this without using JSON, it doesn't ensure that all of the data is safe to pass, e.g. embedded </script> tags. Using JSON will encode your data in a way that prevents this, and you decode it on the JavaScript side with e.g. json2.js.
You're not really using JSON in anything here. You're merely generating an array of strings for javascript and use it in a vvery straightforward manner.
If you wish to transform the JSON to javascript object(s) you need to modify your program and you need a JSON parser. There are several implementations of JSON-parsers, but you mentioned jQuery so you could use: http://api.jquery.com/jQuery.parseJSON/
Parsing with jQuery, however, requires your JSON to be strictly formatted (from v1.4). See http://json.org/ about the correct form. Basically in your situation you should put double quotes around your strings and put the whole array inside square brackets.
Your results should be something like this:
strItems = '['
Foreach(DataRow dr in dvItems.Table.Rows) //dvItems is a DataView
{
// TODO: Escape dr("ItemTitle") so it conforms to http://json.org/ => String
strItems &= "\"" & dr("ItemTitle") & "\"," //strItems is a String
}
strItems = strItems.Trim(",")
strItems &= ']'
<script type="text/javascript">
var jsonArr = <%=strItems%>;
var data = jQuery.parseJSON(jsonArr);
AutoComplete_Create('<%=txtItem.ClientId %>', data);
</script>

How to parse JSON in JavaScript to take value

I am really stuck in parsing a JSON string and take it's values. I got the JSON string as
{"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"fred#websecurify.com", "usergroup_id":"1","status":"1","ip_enable":"N","priv":"0","expire":""},"data":{ "1":{"5":{"last_update":"2010-12-13 16:16:16","status":"0"},"3":{"last_update":"2010-12-13 16:41:48","status":"1"}},"2":{"6":{"last_update":"2010-12-13 16:41:48","status":"1"}}},"server_array":[{"id":"1","name":"anes.yyy.net"},{ "id":"2","name":"neseema.xxx.net"}],"service_array":[{"id":"5","name":"POP3"}, {"id":"6","name":"Cpanel"},{"id":"3","name":"SMTP"}],"sort_by":"servername", "sort_order":"ASC","pagelinks":"","totrows":"2","offset":"0","limitvalue":"10", "rows_monitor":2,"current":"monitor","uri":false}
How to Parse this and take the Results for further
processing in JavaScript
You should use jQuery.parseJSON. It will use native JSON if available, and only use eval if necessary, after a sanity check.
Use JSON.parse (redirected from http://json.org), alternatively MDN
Json is already some javascript. so parsing is just using eval
like:
var foobar = eval(yourjson);
alert(foobar.user);
Also jquery has some function for it jquery.parseJSON
like:
var foobar = $.parseJSON(yourjson);
Jquery is better because it would make some checks and perform better.
First, download jQuery.
Second, include it in your page.
Third, if your variable is this:
var jsonString = '{"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"fred#websecurify.com", "usergroup_id":"1","status":"1","ip_enable":"N","priv":"0","expire":""},"data":{ "1":{"5":{"last_update":"2010-12-13 16:16:16","status":"0"},"3":{"last_update":"2010-12-13 16:41:48","status":"1"}},"2":{"6":{"last_update":"2010-12-13 16:41:48","status":"1"}}},"server_array":[{"id":"1","name":"anes.yyy.net"},{ "id":"2","name":"neseema.xxx.net"}],"service_array":[{"id":"5","name":"POP3"}, {"id":"6","name":"Cpanel"},{"id":"3","name":"SMTP"}],"sort_by":"servername", "sort_order":"ASC","pagelinks":"","totrows":"2","offset":"0","limitvalue":"10", "rows_monitor":2,"current":"monitor","uri":false}';
then,
var parsedJson = jQuery.parseJSON(jsonString);
will give you the desired parsed object that's ready for manipulation.
I tried out your JSON string on JSONLint and it says it's valid, so you should have no problems with it.
you probably got your json in som String variable
var json = '{"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"fred#websecurify.com", "usergroup_id":"1","status":"1","ip_enable":"N","priv":"0","expire":""},"data":{ "1":{"5":{"last_update":"2010-12-13 16:16:16","status":"0"},"3":{"last_update":"2010-12-13 16:41:48","status":"1"}},"2":{"6":{"last_update":"2010-12-13 16:41:48","status":"1"}}},"server_array":[{"id":"1","name":"anes.yyy.net"},{ "id":"2","name":"neseema.xxx.net"}],"service_array":[{"id":"5","name":"POP3"}, {"id":"6","name":"Cpanel"},{"id":"3","name":"SMTP"}],"sort_by":"servername", "sort_order":"ASC","pagelinks":"","totrows":"2","offset":"0","limitvalue":"10", "rows_monitor":2,"current":"monitor","uri":false}';
now you can easily parse it via jQuery (you also can parse it via native javaScript eval, but there are some security issues, badly formated input string f.e., that is covered with jQuery and not in eval)
result = jQuery.parseJSON(json);
Now you can easily acces your json object
alert('Hello user, your name is ' + json.user.firstname);
You don't need jQuery, in ECMAScript5 JSON object will be supported natively and with it you can use JSON.parse method to parse a string into a JS object. IE9 will support ES5 and FF and Chrome already do.
For the moment you can use json2.js (you can look at the source here) as fallback for the browsers that don't support JSON natively.

Categories

Resources