Reputation: 636
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.
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.
Upvotes: 2
Views: 606
Reputation: 2540
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.
Upvotes: 2