Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
                }
            }
        }
like image 660
Your Friend Ken Avatar asked Aug 03 '09 19:08

Your Friend Ken


2 Answers

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"]));
  }
like image 189
Zhaph - Ben Duguid Avatar answered Nov 16 '22 13:11

Zhaph - Ben Duguid


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));
like image 22
Your Friend Ken Avatar answered Nov 16 '22 14:11

Your Friend Ken