最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - What are some best practices for dynamically adding javascript in an asp.net page? - Stack Overflow

programmeradmin0浏览0评论

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
                }
            }
        }

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
                }
            }
        }
Share Improve this question asked Aug 3, 2009 at 19:32 Your Friend KenYour Friend Ken 8,8683 gold badges33 silver badges42 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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"]));
  }

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));

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.

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"));
}
发布评论

评论列表(0)

  1. 暂无评论