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.

-------------Problems Reply------------

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.

Category:javascript Views:5 Time:2018-12-01

Related post

  • how to assign a block of html code to a javascript variable (to invoke a javascript call) 2010-08-08

    I want to assign a block of html code to a js variable the html code is <script>alert('test');</script> I want to do this var script = "<script>alert('test');</script>"; document.getElementById('test').innerHTML = script; but

  • Extending MaRuKu to generate raw html tags, md_html escapes html 2010-08-09

    I'm working in the Insitiki code and trying to extend the maruku syntax to generate some custom html tags. Example: |youtube 0FWPr6u8YF | Should print the html code as follows: <object data='' style='width:425px

  • How to assign ASP.NET hidden field value to JavaScript variable? 2012-01-24

    Following is the code snippets taken from // pre-selected tags values: [ 'javascript', 'css', 'jquery']; I want to assign values with some hidden field

  • html element id as javascript variable 2012-03-16

    Consider the following code: <html> <head></head> <body> <div id='test' class='blah'> <a href='' id='someLink'>click!</a> </div> </body> </html> So I just recently discov

  • JSF wont allow to generate html tags through jquery & javascript? 2011-03-16

    I'm using jsf 2.0 ,richfaces 4.0 to implement my application. I used some times jQuery & javascript function for show & hide. But when I generate tags in xhtml page then it wont allow me. Foe e.g: I want to append image for rich:autocomplete

  • html tag thead effect javascript to run 2013-12-03

    I have a table. The items in the thead contains one checkbox. If I click the check box "selectAll" it checks all the checkboxes in the table. I had to add jquery tablesorter. For that purpose I had to use thead. My javascript stopped working because

  • Does googlebot recognize an HTML tag altered by javascript ? 2011-03-23

    I have a search engine on my website and it works via ajax. I want to have a specific <title> for each search attempt. To achive that I have to alter every time after I recieve a response from ajax. Do you have any idea if googlebot will see th

  • Changing HTML tag attributes with javascript 2011-05-16

    I'm trying to get what I think is a really nice bit of HTML5 in my website - the placeholder attribute for input fields. But the way I've got it in my website degrades badly. Because I've skipped labels for the fields and used the placeholder as its

  • HTML tags, CSS and Javascript developer tool for Safari? 2012-03-07

    Are there and tools for Safari like there are Developer Tools for IE8 and Firebug for Firefox? --------------Solutions------------- yes, enable it in the menus edit>preferences>advanced> show Develop menu in menu bar try https://developer.ap

  • assigning retrieved data using ajax to a javascript variable 2011-08-04

    im new to javascript and ajax, i am trying to figure out how to assign to a global variable the retrieved data using ajax. my code looks like this: $('#store').live('pagecreate',function(event){ var address; $.ajax({ type: "POST", url: "testing.php",

  • How can I insert html code inside a javascript variable? 2011-11-14

    So I am pulling information from google calendar and I need to divide the variables I am receiving so I can display them in different divs. So what i need to do is something like this var divMonth = '<div id ="rawr">'; var divMonthClose = '<

  • How to remove a tag from a javascript variable 2014-08-08

    How to remove some part of data from a variable This is my jsfiddle When once clicked on submit , i want to remove this part of text '<p class="tcPriceWrap">25</p>' So that i can have toppings array with only

  • preg_match parsing html tags and insert into variable 2011-08-02

    I have the following tags and I want to extract buying and selling price: 2.9450 and 3.0150 <tr bgcolor="#E8EFF3"> <td width="25%" align="center" valign="middle" class="tx11"> USD</td> <td width="8%" class="tx11">RON </td

  • Using HTML tags in JavaScript strings while complying with W3C rules 2009-11-28

    Here's my code: <a href="#"> <img src="myimage.jpg" onmouseover="showDescription( 'Text', 'Text with HTML tags in them<br />More text');" onmouseout="revertDescription();" alt="Image description"> The W3C Markup Validator doesn't li

  • How we can find attach function in a html tag in javascript 2011-07-15

    Suppose we have a html tag and some javascript function is attached on that by addEvenetListner or attachEvent (with tag id or name but not inline), and if we need find out that which function is attach on that tag, then what is good way for find tha

  • Declare HTML tag as a string in VB.NET 2010-07-11

    I'm trying to assign the following HTML as a value to variable type string 'here's the tag '$("#close").click(function(){$.notifyBar({ html: "Click 'close' to hide notify bar", close: true, delay: 1000000 });}); Dim htmltag = "$("#close").click(funct

  • How to include multi-line html from django template into javascript variable 2011-04-03

    From a Django template, I would like to include an html snippet from a file, say mysnippet.html: <div> blah </div> into a javascript variable: <script type="text/javascript"> var myvar = {% include 'mysnippet.html' %} </script

  • is it wrong to use jquery to output html tags? 2011-01-24

    Just wondered is it bad practice to output html tags with javascript. For example say I had a table and on the page load an ajax request gets the data to populate it. For each row of data I'm going to need to output another row, something like this:

  • reading html file to javascript variable (windows) 2011-01-29

    hey, I want to read an html file into a javascript variable that will contain it as a string. is there an appropriate function, for example, that takes the file path as a parameter. thanks --------------Solutions------------- Although XMLHttpRequest

  • How to read HTML tag values in C# Razor View 2012-04-13

    I have a value in my span, which i want to compare with C# variable, is it possible ?? If yes, then How ?? I can get the Html tag values in Jquery variable, but still not succeeding to get it to compare it with a C# variable value in Razor View. HTML

  • javascript - how to wrap text blocks in containing html tags in IE 2011-06-03

    I'm unable to figure this out in Internet Explorer, but I want to be able to wrap a text block with tags that contain various html tags in it. I am writing a highlighting function where you highlight text with your mouse and the selection you highlig

  • javascript, jQuery and HTML tags: how to check if tags are closed 2011-12-08

    I've had this problem many times: I create HTML dynamically via jQuery, and in this HTML code I'd like to know if all the tags are properly closed. If I try to see what's in the DOM with Firebug, it automagically close every tag that is not properly

  • How to modify html tag using javascript to add a target _blank 2012-01-30

    I have the following link: x = <a href=""></a> how can I use javascript to modify the url, to add a target _blank? String.prototype.parseURL = function() { return this.replace(/[A-Za-z]+:\/\/[A-Za

  • What html tags support the onload/onerror javascript event attributes? 2009-03-24

    I'm familiar with the typical use of onload, as in the following: <body onload="alert('Hello, World!');"> ... </body> What are all the html elements that fire a load event? (thus executing javascript supplied in an onload attribute) For e

  • embed HTML tag in JavaScript 2009-05-12

    I'd like to embed an html tag in Javascript, between the script> tag Thanks --------------Solutions------------- Is E4X what you're looking for? It allows you to embed XML/XHTML within your JavaScript, like this: var someXml = <div><b>

Copyright (C), All Rights Reserved.

processed in 0.149 (s). 11 q(s)