Is there a better way to get ClientID's into e

2020-02-26 10:33发布

I know this has been asked before, but I've found a different way to get references to controls in external JS files but I'm not sure how this would go down in terms of overall speed.

My code is

public static void GenerateClientIDs(Page page, params WebControl[] controls) {

        StringBuilder script = new StringBuilder();
        script.AppendLine("<script type=\"text/javascript\">");

        foreach (WebControl c in controls) {
            script.AppendLine(String.Format("var {0} = '#{1}';", c.ID, c.ClientID));
        }

        script.AppendLine("</script>");

        if (!page.ClientScript.IsClientScriptBlockRegistered("Vars")) {
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "Vars", script.ToString());
        }
    }

This was I can reference the id of the aspx page in my JS files.

Can anyone see any drawbacks to doing things this way? I've only started using external JS files. Before everything was written into the UserControl itself.

2条回答
够拽才男人
2楼-- · 2020-02-26 11:10

Well, the method can only be used once in each page, so if you are calling it from a user control that means that you can never put two of those user controls on the same page.

You could store the control references in a list until the PreRender event, then put them all in a script tag in the page head. That way you can call the method more than once, and all client IDs are put in the same script tag.

Something like:

private const string _key = "ClientIDs";

public static void GenerateClientIDs(params WebControl[] controls) {
   Page page = HttpContext.Current.Handler As Page;
   List<WebControl> items = HttpContext.Current.Items[_key] as List<WebControl>;

   if (items == null) {
      page.PreRender += RenderClientIDs;
      items = new List<WebControl>();
   }

   items.AddRange(controls);

   HttpContext.Current.Items[_key] = items;
}

private static void RenderClientIDs() {
   Page page = HttpContext.Current.Handler As Page;
   List<WebControl> items = HttpContext.Current.Items[_key] as List<WebControl>;

   StringBuilder script = new StringBuilder();
   script.AppendLine("<script type=\"text/javascript\">");
   foreach (WebControl c in items) {
      script.AppendLine(String.Format("var {0} = '#{1}';", c.ID, c.ClientID));
   }
   script.AppendLine("</script>");

   page.Head.Controls.Add(new LiteralControl(script));
}
查看更多
3楼-- · 2020-02-26 11:32

Check this out: http://weblogs.asp.net/joewrobel/archive/2008/02/19/clientid-problem-in-external-javascript-files-solved.aspx

Looks like it takes care of the dirty work for you (something like Guffa's answer). It generates a JSON object (example) containing server IDs and client IDs, so you can do something like this in your JavaScript:

var val = PageControls.txtUserName.value;
查看更多
登录 后发表回答