How do you set the “Visible” property of a ASP.NET control from a Javascript function?

后端 未结 9 553
不知归路
不知归路 2021-01-17 09:49

Bascially I want to know the best way to hide/show an ASP.NET control from a Javascript function. I figured I would just access the control in Javascript using:

<         


        
相关标签:
9条回答
  • 2021-01-17 10:09

    You can't hide/ show the ASP.NET version of the control as that only exists in a server context. To use JavaScript you need to play with the controls style/ visibility state.

    The only kind-of way to do it would be to wrap the control in an UpdatePanel and have something like this:

    <asp:UpdatePanel ID="panel" runat="server">
      <ContentTemplate>
        <asp:TextBox ID="myTextBox" runat="server" />
      </ContentTemplate>
      <Triggers>
        <asp:AsynchronousPostbackTrigger ControlID="button" EventName="Click" />
      </Triggers>
    </asp:UpdatePanel>
    <asp:Button ID="button" runat="server" OnClick="toggle" Text="Click!" />
    

    Then you need this in your code behind:

    protected void toggle(object sender, EventArgs e){
      myTextBox.Visibility = !myTextBox.Visibility;
    }
    

    Now when you click the button an async postback occurs and it will refresh the UpdatePanel.

    Note: This is not a good solution, as it'll be a very heavy AJAX request, because you need to submit the ViewState.

    Also, it may not be 100% right, I did that from memory.

    0 讨论(0)
  • 2021-01-17 10:10

    I think the best solution is to put your ASP control inside a div and set the property display to the div element.

    <div id="divTest">            
       <asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
    </div>
    
    <script type="text/javascript">
        SIN JQuery
        document.getElementById('divTest').style.display = "none";
    
        CON JQuery
        $('#divTest').hide();
    </script>
    
    0 讨论(0)
  • 2021-01-17 10:16

    instead of using visible, set its css to display:none

    //css:
    .invisible { display:none; }
    
    //C#
    txtEditBox.CssClass = 'invisible';
    txtEditBox.CssClass = ''; // visible again
    
    //javascript
    document.getElementById('txtEditBox').className = 'invisible'
    document.getElementById('txtEditBox').className = ''
    
    0 讨论(0)
提交回复
热议问题