Question

I have an ascx control which has a literal placed on it during design time. At run time, in Page_Load, I set the literal's text property to a javascript that I retrieve from a database. However, it appears that the javascript code is not evaluated. What do I need to do in order to get the script evaluated?

In .ascx:

<asp:Literal id="litTags" runat="server"></asp:Literal>

In ascx.cs:

protected void Page_Load(object sender, EventArgs e)
  {
      //Set literal's text to the script
      litTags.Text = "Javascript tag and script from database";
  }
Was it helpful?

Solution

Make sure you wrap that js code in the proper tag:

<script type="text/javascript">'
// js code here
</script>

OTHER TIPS

You need to do this with the ClientScript.RegisterClientScriptMethod.

Add a ScriptManager on your master page or parent page.

Then use thise code (reference: http://msdn.microsoft.com/en-us/library/bahh2fef.aspx)

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptname", "var variable = '" + dbVar + "';", True);

or, if as a start up script (reference: http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx)

ClientScript.RegisterStartupScript(this.GetType(), "scriptname", "var variable = '" + dbVar + "';", True);

You don't need the literal control that way.

There must be an error in your Javascript, for example trying to manipulate a part of the DOM that has not loaded before your script.

The following evaluates as expected:

protected void Page_Load(object sender, EventArgs e)    {

        StringBuilder sb = new StringBuilder();

        sb.Append("<script type='text/javascript'>" + Environment.NewLine);
        sb.Append("alert('hello world');" + Environment.NewLine);
        sb.Append("</script>" + Environment.NewLine);

        litTags.Text = sb.ToString();

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top