在asp.net页面中动态添加javascript的最佳实践有哪些?

You*_*Ken 6 javascript c# asp.net json

这是我正在处理的实际代码,它从查询字符串中获取ID,检索对象并解析为json.我将需要存储和操作此数据客户端.将生成的json字符串设置为客户端对象的最佳方法是什么?

注意:NewObjectCase是一个类,其方法Get(strID)返回一个新的Object.Tools.GetQueryObject(string key)是一个返回键的字符串值的metod

    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
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

Zha*_*uid 5

完成工作的几种简单方法:

1:使用ClientScriptManager.RegisterClientScriptBlock调用直接在页面上插入脚本:

  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);
  }
}
Run Code Online (Sandbox Code Playgroud)

2:代码隐藏的属性,在页面端引用:

在.aspx页面中,如下所示:

<script type="text/javascript">
  var myValue = <%=ValueFromCodeBehind%>
</script>
Run Code Online (Sandbox Code Playgroud)

在您的代码中,您声明变量,并确保它已设置:

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"]));
  }
Run Code Online (Sandbox Code Playgroud)


Pic*_*ght 0

在母版页中添加 Javascript 文件链接上找到了这个

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