Ross
Ross

Reputation: 11

Html tag with runat="server" thrown RegisterForEventValidation can only be called when rendering

in my project in dot.net WebForm I am implementing a dynamic tab menu. The tab control is managed in the aspx file. When a tab is selected it takes care of loading the corresponding ascx file (UserControl). Through the RenderControl I was able to load the UserControls.

Ajax call to handle tab switching


$('a[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
    var targetId = $(e.target).data('bs-target').substring(1);
    loadUserControl(targetId);
});

function loadUserControl(userControlId) {
    $.ajax({
        type: "POST",
        url: "Page.aspx/LoadUserControl",
        data: JSON.stringify({ userControlId: userControlId }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            $('#tabContent').html(response.d);
        },
        error: function (error) {
            console.log(error);
        }
    });
}

WebMethod to render the UserControl

[WebMethod]
public static string LoadUserControl(string userControlId)
{
    if (HttpContext.Current.Handler is Page page)
    {
        var userControl = page.LoadControl($"{userControlId}.ascx");
        using (StringWriter stringWriter = new StringWriter())
        {
            using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
            {
                userControl.RenderControl(htmlWriter);
                return stringWriter.ToString();
            }
        }
    }
    return string.Empty;
}

Problem:

The problem is that the moment an html tag like input or aspx:Button has runat="server" as attribute, I get this exception: RegisterForEventValidation can only be called during Render.

Browsing the internet everyone says that the solution to this problem is to disable the EnableEventValidation attribute in the UserControl page and override the VerifyRenderingInServerForm method as follows:

public override void VerifyRenderingInServerForm(Control control)
{
    /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
       server control at run time. */
}

I know that the EnableEventValidation attribute is related to security, so I would not want to disable it.
Can you give me some clarification on this? I can't find any other solution to this problem.

Upvotes: 1

Views: 160

Answers (0)

Related Questions