locked
Get Controls by ControlID in external javascript file RRS feed

  • Question

  • User1884614354 posted

    Hello folks,

    I was struggling whit including an external javascript file into my project,

    So i wrote this little work around that easily lets me get Controls by there original ID.

    A client site function is registered whit the name GetControl( ControlID ) that returns a handler to the control, this way i don't have to bother whit injecting server code into my javascript.

    Im not sure if this is a safe solution, i'm pretty sure its ok to expose the ID's since they are alread exposed in the ClientID's anyway.

    But i'm slightly concerned about performance maybe the code won't load fast enough, or maybe i'm doing some very bad things here, i don't know, i'd like some feedback.

    Thx in advance !!

    This is the code behind file of the Default page. i don't think adding extra client side or mark up code will add extra relevant info.

    Partial Class _Default
        Inherits System.Web.UI.Page
      
        ' This is a function that will loop trough all TextBox DropDownList CheckBox, etc...  what ever you need
        Public Sub FillWhitControlClientID(ByVal oControl As Control, ByRef ToFill As StringDictionary)
            Dim frmCtrl As Control
            For Each frmCtrl In oControl.Controls
                If TypeOf frmCtrl Is TextBox Or TypeOf frmCtrl Is DropDownList Or TypeOf frmCtrl Is CheckBox Or TypeOf frmCtrl Is Label Then
                    ToFill.Add(frmCtrl.ID, frmCtrl.ClientID)
                End If
                If frmCtrl.HasControls Then
                    FillWhitControlClientID(frmCtrl, ToFill)
                End If
            Next
        End Sub
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
           
            Dim ClientIDs As New StringDictionary
            FillWhitControlClientID(Me.Form, ClientIDs)
            Dim ClientIDText As String = ""
    
            For Each Entry As DictionaryEntry In ClientIDs
                ClientIDText &= """" & Entry.Key & """ : """ & Entry.Value & """," & Environment.NewLine
            Next
            Dim ClientIDScript = "var ControlIDArray = { " & ClientIDText.TrimEnd(","c) & " }" & Environment.NewLine & _
            "function GetControl ( ControlID ){ return $get( ControlIDArray[ ControlID.toLowerCase() ] ) }"
    
            ClientScript.RegisterClientScriptBlock(Me.GetType(), "ControlIDs", "<script type=""text/javascript"">" & ClientIDScript & "</script>")
        End Sub
    
    End Class
    


     

    Wednesday, April 7, 2010 5:16 AM

Answers

  • User645573348 posted

    Two tips for managing asp.net clientid control names and accessing them in javascript:

    If you are using Jquery you should use a CSS selector that way you do not need the clientids and your FE and BE developers can work more harmoniously. Also this allows for quicker changes without the need to recompile anything.

    alert($("input[type='textbox']").value);

    If you are not using Jquery you can drop in a config object that contains all the object names. Something like the following:

    //-------------------------------------
    //in your external javascript file
    
    var InterfaceElements = null;
    
    /* functions that use the InterfaceElements */
    
    function readTextbox(){
      alert(InterfaceElements.myTextBox.value);
    }
    
    //-------------------------------------
    
    <!-- in your aspx file in the html -->
    <script type="text/javascript" src="myexternal.js"></script>
    <script type="text/javascript">
    InterfaceElements = {
    
    myTextBox = '<%=text1.ClientID %>',
    myCheckBox = '<%=check1.ClientID %>',
    myButton = '<%=button1.ClientID %>'
    
    };
    </script>


    This is a little rough around the edges but you should get the point. This allows the FE to define the UI if your not using JQuery and the BE to just need to define the new values going into these fields. You just need to be sure that everything is defined at the proper time so that nothing is null when your expecting it to have a value.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 7, 2010 1:17 PM

All replies

  • User2079231327 posted

    Hi

     

    This example shows the basic way on how to access control from external javascript file (.js). Normally, we use the following line below when accessing control within our JavaScript method in the page.

    document.getElementById('<%= TextBox1.ClientID %>');

    AFAIK, Using  Inline expression like <% %> will not work within external  js files. As a workaround we can pass the id of the control (eg. TextBox) to the funciton as a parameter instead like:

    External JS file:

    function GetControlValue(obj)
    {
    var box =  document.getElementById(obj);
    alert(box.value); // returns the value "Hello ASPNET"
    }

    ASPX:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Untitled Page</title>
    <script src="JScript.js" type="text/javascript"></script>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="TextBox1" Text="Hello ASPNET" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="GetControlValue('TextBox1');" />
    </div>
    </form>
    </body>
    </html>

     

    As you noticed we passed the ID of TextBox control which is "TextBox1" to the Javascript function and get the value to perform certain actions or conditions based on the value.

    <!-- end article body -->

    <INPUT id=ctl00_ContentPlaceHolder1_BlogDetail1_hidAnonymousComments type=hidden value=False name=ctl00$ContentPlaceHolder1$BlogDetail1$hidAnonymousComments>

     

    Thanks

    mark the answer if solves your issue

    Wednesday, April 7, 2010 8:24 AM
  • User-768391503 posted

    ClientID's have nothing to do with security. They are to make sure that it is impossible to have name collisions between elements on the page when you add additional components.

    Eric


    Wednesday, April 7, 2010 8:39 AM
  • User1884614354 posted

    <base href="/"> <link rel="stylesheet" href="http://forums.asp.net/tiny_mce/jscripts/tiny_mce/themes/advanced/skins/default/content.css">

    As i pointed out in my post, i am fearly sure that exposing the ClientID's is not a security problem at all.

    I would just like some general feedback on my code.

    maybe code is already present in the .net framework that has the same functionality
    or maybe passing all the ClientIDs isn't such a good reason for some other reason , or maybe my coude won't work in some situation?

    I don't know, thats why i'm here, to get some feedback on my code, if that's possible.

    @ sKyIsMyLiMit

    Your code will not work, whit the code you've written,you would infact generate the exact error that i'm by passing whit my script,
    as the ControlID is not the same as the ClientID

    Wednesday, April 7, 2010 8:55 AM
  • User1884614354 posted

    i just saw that my code wasn't showing correctly, sorry for that!

    Now you can see the code correctly!  

    Wednesday, April 7, 2010 9:03 AM
  • User645573348 posted

    Two tips for managing asp.net clientid control names and accessing them in javascript:

    If you are using Jquery you should use a CSS selector that way you do not need the clientids and your FE and BE developers can work more harmoniously. Also this allows for quicker changes without the need to recompile anything.

    alert($("input[type='textbox']").value);

    If you are not using Jquery you can drop in a config object that contains all the object names. Something like the following:

    //-------------------------------------
    //in your external javascript file
    
    var InterfaceElements = null;
    
    /* functions that use the InterfaceElements */
    
    function readTextbox(){
      alert(InterfaceElements.myTextBox.value);
    }
    
    //-------------------------------------
    
    <!-- in your aspx file in the html -->
    <script type="text/javascript" src="myexternal.js"></script>
    <script type="text/javascript">
    InterfaceElements = {
    
    myTextBox = '<%=text1.ClientID %>',
    myCheckBox = '<%=check1.ClientID %>',
    myButton = '<%=button1.ClientID %>'
    
    };
    </script>


    This is a little rough around the edges but you should get the point. This allows the FE to define the UI if your not using JQuery and the BE to just need to define the new values going into these fields. You just need to be sure that everything is defined at the proper time so that nothing is null when your expecting it to have a value.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 7, 2010 1:17 PM