Your Friend Ken
Your Friend Ken

Reputation: 8868

What are some best practices for dynamically adding javascript in an asp.net page?

This is actual code from what I am working on that takes an ID from the query string, retrieves an object and parses to json. I am going to need to store and manipulate this data client-side. What is the best way to set the generated json string to a client-side object?

Note: NewObjectCase is a class with the method Get(strID) that returns a new Object. Tools.GetQueryObject(string key) is a metod that return the string value of the key

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.Script.Serialization;
    using System.Web.UI.WebControls;

        public partial class Testing: System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    string strJson = new JavaScriptSerializer().Serialize(NewObjectCase.Get(Tools.GetQueryObject("id")));
                    // add in js to page that will set an client-side js object to this generated json
                }
            }
        }

Upvotes: 6

Views: 4582

Answers (4)

Picflight
Picflight

Reputation: 3852

Found this on Adding Javascript file link in Master Page

protected void Page_Load(object sender, EventArgs e)
{
  Page.ClientScript.RegisterClientScriptInclude("somescript", ResolveUrl("some.js"));
}

Upvotes: 0

Zymotik
Zymotik

Reputation: 7397

This will register your script at the top of the page.

ClientScriptManager.RegisterClientScriptBlock Method (Type, Key as String, Script as String)

Adding a type and key makes sure that only one version of the script is added to the page for that type and key.

In this overload of the RegisterClientScriptBlock method, you must make sure that the script provided in the script parameter is wrapped in a element block.

Upvotes: 0

Zhaph - Ben Duguid
Zhaph - Ben Duguid

Reputation: 26976

Couple of simple ways of getting the job done:

1: Use the ClientScriptManager.RegisterClientScriptBlock calls to insert the script directly on the page:

  protected void Page_Load(object sender, EventArgs e) {

    // Not sure what your Tools.GetQueryObject is doing, but it should at 
    // the least be performing a UrlDecode to convert the string from any 
    // Url encoding, and as you're about to pass this back to javascript, 
    // you should also HtmlEncode it.
    string valueFromCodeBehind = "var myValue = " +
              Server.HtmlEncode(Server.UrlDecode(Request.QueryString["id"]));

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Output the script block to the page.
    // Notes:
    // 1) I'm passing true as the final parameter to get the script manager
    //    to auto generate the script tags for me.
    // 2) You might need to call "RegisterStartupScript" if you need the  
    //    JS variables earlier in the page.
    cs.RegisterClientScriptBlock(this.GetType(),
                                 "SetValues", 
                                 valueFromCodeBehind,
                                 true);
  }
}

2: Property on the code-behind, referenced on the page side:

In your .aspx page, something like this:

<script type="text/javascript">
  var myValue = <%=ValueFromCodeBehind%>
</script>

In your code behind, you declare the variable, and ensure it's set:

public partial class Testing: System.Web.UI.Page { 
  protected string ValueFromCodeBehind;

  protected void Page_Load(object sender, EventArgs e) {

    ValueFromCodeBehind = 
              Server.HtmlEncode(Server.UrlDecode(Request.QueryString["id"]));
  }

Upvotes: 5

Your Friend Ken
Your Friend Ken

Reputation: 8868

This is my original plan but it seemed like there could be a better way to add a json object and in the intellisence I noticed it has [Deprecated] next to Page.RegisterClientScriptBlock().

Page.RegisterClientScriptBlock("clientScript",
    string.Format("<script type='text/javascript' language='javascript'>objCase = {0}</script>", strJson));

Upvotes: 1

Related Questions