How to create a control with ValidationGroup and custom validation?

I want to make panels Visibility trueor falsebased on the result Func.

I have a page with controls, as in the following code:

<asp:Panel ID="Panel2" runat="server">
    <asp:Panel ID="Panel3" runat="server">
        <c:PermissionPanel ID="P1" runat="server" ValidationGroup="Val1">
            Validation Group 1 - OK
        </c:PermissionPanel>
    </asp:Panel>
</asp:Panel>

<c:PermissionPanel ID="P2" runat="server" ValidationGroup="Val1">
    Validation Group 1 - OK
</c:PermissionPanel>

<hr />

<c:PermissionPanel ID="P3" runat="server" ValidationGroup="Val2">
    Validation Group 2 - OK
</c:PermissionPanel>

<asp:Panel ID="Panel4" runat="server">
    <asp:Panel ID="Panel1" runat="server">
        <c:PermissionPanel ID="P4" runat="server" ValidationGroup="Val2">
            Validation Group 2 - OK
        </c:PermissionPanel>
    </asp:Panel>
</asp:Panel>

In short, I have 4 PermissionPanelthat can be inside other controls.

The code is PermissionPanelas follows:

public class PermissionPanel : Panel
{
    public delegate bool OnValidate();
    public event OnValidate Validate;

    public string ValidationGroup { get; set; }

    protected override void OnPreRender(EventArgs e)
    {
        this.Visible = (Validate != null ? Validate() : false);

        base.OnPreRender(e);
    }
}

I want to get everything PermissionPanelfrom the page and add an event for each of them in accordance with its group, for example:

protected void Page_Load(object sender, EventArgs e)
{
    // Magic code here. Linq is very welcome
    // GetPageControls<PermissionPanel>("Val1").AddEvent(() => return true);
    // GetPageControls<PermissionPanel>("Val2").AddEvent(() => return false);
}

The above code will make all panels with ValidationGroup== Val1visible, and Val2will not be displayed.

So the questions are : How can I achieve this? Is there a better way to do this?


, Func, , . :

// If post owner is the logged user, show controls like edit and delete
() => return (user != null && user.ID == post.UserID);
+3
1

, : . , , , PermissionPanel.

-, , , PermissionPanel, Page.Items .

PermissionPanel - :

protected override void CreateChildControls()
{
     base.CreateChildControls();

     List <PermissionPanel> panels;

     if (Page.Items["PermissionPanels"] == null)
         Page.Items["PermissionPanels"] = panels = new List <PermissionPanel>();
     else
         panels = Page.Items["PermissionPanels"] as List <PermissionPanel>;

     panels.Add(this);
}

OnPreRender Page.Items["PermissionPanels"] .

+2

Source: https://habr.com/ru/post/1768540/