ASP.NET: Create new CSS class programmatically from User Control?
I have a UserControl which contains, among other things, this AJAX modal popup extender:
<ajax:ModalPopupExtender ID="MPE" runat="server"
TargetControlID="btnChangePassword" PopupControlID="pnlPasswordChanging"
BackgroundCssClass="modalBackground" DropShadow="true"
CancelControlID="btnCancel" OnCancelScript="ULC_ChangePw_CancelBtnClick();" />
Nothing special here. The problem comes from that BackgroundCssClass
attribute—it requires a CSS class called modalBackground. Unfortunately I cannot add a CSS class from a user control in a way that survives postbacks.
If I add my modalBackground class to the .ascx page:
<style type="text/css">
.modalBackground
{
background-color: #A1A1A1;
filter: alpha(opacity=70);
opacity: 0.7px;
}
</style>
...it will show up property when first loaded, but not so after subsequent postb开发者_StackOverflow社区acks. Of course I could define modalBackground within the page itself, or within a seperate, standalone CSS file that is called by the user control, but neither solution will work for me.
Is there no way to create a CSS class programmatically and add it to the page? Basically I'm looking for a CSS equivilant to Javascript's RegisterClientScriptBlock
function:
Dim controlNameScript = String.Format("<script type='text/javascript'> var AppMenuName = '{0}' </script>", Me.ClientID)
Me.Page.ClientScript.RegisterClientScriptBlock(myType, "ControlName", controlNameScript)
Thanks!
If the CSS is defined in your .ASCX file, it should be rendered every time, postback or not. Unless the control itself is set to Visible="false".
One workaround is to define the CSS code within an asp:Literal block on your control. Your control can then expose a public function that simply returns the contents of that literal to the caller. If a host is going to make your control invisible, they can grab the CSS code using that public function, and place it within the head section of the page. In that way, the CSS definition should always be there, regardless of the Visibility setting of the control.
In the larger scheme of things, Adam is correct: it's better to keep your CSS code in .CSS files wherever possible.
It would be standard to include this class in a css file you reference in your site's master page, or the specific page itself. Why would this not work for you?
Okay here's all I needed to solve my problem:
Me.Page.Header.Controls.Add(
New LiteralControl("<style type=""text/css""> .modalBackground {background-color: #A1A1A1; filter: alpha(opacity=70); opacity: 0.7px;} </style>"))
精彩评论