Show hide div using codebehind

前端 未结 8 2073
难免孤独
难免孤独 2020-12-30 00:29

I have a DropDownList for which I am trying to show a div OnSelectedIndexChanged but it says OBJECT REQUIRED.

I a

8条回答
  •  清歌不尽
    2020-12-30 01:02

    There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.

    Rendering and Visibility

    There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.

    Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.

    The decision to render the div or not can now be done in the code behind class like so:

    myDiv.Visible = someConditionalBool;
    

    If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.

    Client Side Hiding

    Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.

    Hiding in the Code Behind Class

    To hide an element that you want rendered to the page but hidden is another simple single line of code:

    myDiv.Style["display"] = "none";
    

    If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).

    myDiv.Style.Remove("display");
    // -- or --
    myDiv.Style["display"] = "inline";
    

    Hiding on the Client Side with javascript

    Using plain old javascript, you can easily hide the same element in this manner

    var myDivElem = document.getElementById("myDiv");
    myDivElem.style.display = "none";
    
    // then to show again
    myDivElem.style.display = "";
    

    jQuery makes hiding elements a little simpler if you prefer to use jQuery:

    var myDiv = $("#<%=myDiv.ClientID%>");
    myDiv.hide();
    
    // ... and to show 
    myDiv.show();
    

提交回复
热议问题