c# - Assign a raw HTML tag to a JavaScript variable -
i'm working on existing asp.net application , came across interesting piece of javascript i've been wondering about.
a few variables being declared literals, , aren't in strings. example, done:
<script type="text/javascript"> var jsondata = <asp:literal id="myjsonobject" runat="server" />; ...... </script>
and in server side code(c#), these tags being altered jsontextwriter
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 causing jsondata variable able used json object in client side code.
what i've noticed is, if put single quotes around tag , change to:
<script type="text/javascript"> var jsondata = '<asp:literal id="myjsonobject" runat="server" />'; ...... </script>
this doesn't work it's no longer coming across json object, actual string. however, expect, when it's plain tag, i'm receiving several syntax errors visual studio.
so question is:
is that's acceptable or should avoid keeping things around? yeah, it works, doesn't right me.
i've found few different questions seem related here, none seem provide insight on particular situation.
in short: yes, looks acceptable. appears 1 of intended use-cases of <asp:literal>
tag. since you're writing javascript object literal, won't need single-quotes, since change how code works.
the thing note <asp:literal>
isn't html tag, , therefore not make user is. <asp:literal>
tag gets pre-processed asp.net before page sent user (since have runat="server"
specified); therefore, processed regardless of surrounding content , replaced entirely resolved string value. thus, rendered page transformed (on server-side) this:
var jsondata = <asp:literal id="myjsonobject" runat="server" />;
to this:
var jsondata = { "someproperty" : "somevalue" };
this way of transferring rich data constructed on server-side client-side javascript without having write out raw javascript page.
if wanted json-formatted string instead, doing you're doing , calling json.stringify(jsondata)
afterwards best bet.
Comments
Post a Comment