I have a div and 4 drop-down controls.
Default div is hidden using Style="display:none"
.
First drop-down don't have autopostback event.
Div's display property is changed on few values of 1st drop-down. Once its is visible. User can change values in drop-down field 2/3/4 which is having auto postback true.
As user changes value in any of the 2-5 drop-down controls, postback triggers and set the display property of that Div to Style="display:none"
.
How can I retain display property of div.
This is on .aspx page
The styles are not part of the data that are contained in the PostBack. In order to include them, you can create a hidden field on the page that you also set whenever your client code changes the visibility of the div.
<asp:HiddenField ID="hidden" runat="server" />
When the PostBack arrives at the server, you evaluate the Value
property of the hidden field and set the style on the div
so that it matches the state that was stored in the hidden field. In order to be able to change the style on the div
in .NET code, you need to make sure that runat="server"
is specified:
<div ID="myDiv" runat="server">
<!-- ... -->
</div>
Sample
The following sample shows how you can use a hidden field to transfer the visibility to the server and restore it on the client. In ASPX, there is the div
, the hidden field to store the visiblity and a script that sets the visiblity of the div
and also the value of the hidden field:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div id="myDiv" runat="server" style="display:none;">
Div is visible
</div>
<asp:HiddenField ID="myHidden" runat="server" />
<input type="button" value="Toggle visiblity" onclick="javascript:toggleDiv()" />
<asp:Button ID="btn" runat="server" Text="Postback" />
<script type="text/javascript">
function toggleDiv()
{
$(myDivId).toggle();
$(myHiddenId).val($(myDivId).css('display'));
}
</script>
</asp:Content>
Important to note is that the div
and the hidden fields get special ASP.NET client ids that do not necessarily match the ids of the tags in the ASPX-file. Therefore, I register a startup script that defines variables with the ids (myDivId
and myHiddenId
):
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "DivId",
"var myDivId = '#" + myDiv.ClientID + "';" + Environment.NewLine +
"var myHiddenId = '#" + myHidden.ClientID + "';",
true);
}
When a postback occurs, the value of the hidden field is transferred to the server and can be used. I've defined a PreRender
event handler, that restores the visibility of the div
:
protected void Page_PreRender(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(myHidden.Value))
myDiv.Style[HtmlTextWriterStyle.Display] = "none";
else
myDiv.Style[HtmlTextWriterStyle.Display] = myHidden.Value;
}