Retrieve contents of HtmlGenericControl inside ASCX WebControl

All we need is an easy explanation of the problem, so here it is.

I have an HtmlGenericControl which is a simple DIV with runat=server

This Control is embedded inside of an ASCX WebControl which resides on multiple pages. At Page_Load this element is populated by a repeater that is data-bound to database data that is Page Specific.

The trouble I’m having is ASCX WebControls don’t seem to read the contents of their own elements very easily.

So far this has failed:
How do I get the HTML output of a UserControl in .NET (C#)?

I’m looking for a way to get the contents of the HtmlGenericControl inside of a button click. How would I do that?

Simplifying previous question. Retrieve HTML of specific element in ASCX

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

OK, I got it working (I think…)

Output

enter image description here

ASPX Code behind

    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }

ASPX markup

%@ Page EnableEventValidation="false" .....

User control code behind

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            var d = new QuestionsContext().GetQuestions();

            this.repeater.DataSource = d;
            this.repeater.DataBind();
        }
    }

    protected void getContent_Click(object sender, EventArgs e)
    {
        var sb = new StringBuilder();

        this.generic.RenderControl(new HtmlTextWriter(new StringWriter(sb)));

        string s = sb.ToString();

        this.Trace.Warn(Server.HtmlEncode(s));
        this.message.Text = Server.HtmlEncode(s);
    }

User control markup

<div runat="server" id="generic">
    <asp:Repeater runat="server" ID="repeater" >
        <ItemTemplate>
            <%# Eval("QuestionText") %>
        </ItemTemplate>
    </asp:Repeater>
</div>

<br />
<asp:Button Text="Get content" ID="getContent" runat="server" OnClick="getContent_Click" />
<br />
<asp:Label ID="message" runat="server" />

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply