Lajos Arpad Lajos Arpad - 5 months ago 7
Vb.net Question

Do something once at maximum with a Control during a page life-cycle

I have implemented a color picker control in a web forms project and would like to make sure that CSS/JS is loaded maximum once. I have tried the following:

Protected Shared _clientNeeded As Boolean = True
Public Sub NeedClient()

If (_clientNeeded) Then
_clientNeeded = False
Else
Return
End If
'Loading the client-side
End Sub


The problem is that after building,
_clientNeeded
is true at first but then becomes false and will be false forever, so Shared, as my try did not fulfill my goal. So, how could I make sure that loading the client-side will occur if there are color pickers, but not more than once.

Answer

You could implement the property with a combination of Context.Items and ViewState. When the page loads several controls, the value of ClientNeeded can be shared between them through the Context.Items of the page. Once the property has been set, each control can store it in its own ViewState, so that it is maintained as long as the page is active:

protected bool ClientNeeded
{
    get
    {
        object value = ViewState["ClientNeeded"];

        if (value != null)
        {
            return (bool)value;
        }
        else
        {
            value = Context.Items["ClientNeeded"];
            if (value != null)
            {
                ViewState["ClientNeeded"] = value;
                return (bool)value;
            }
            else
            {
                return true;
            }
        }
    }

    set
    {
        Context.Items["ClientNeeded"] = value;
        ViewState["ClientNeeded"] = value;
    }
}