1

When trying to render the HTML of an ascx UserControl from a WebService, I get the error RegisterForEventValidation can only be called during Render.

This is a duplicate of this question. However the answers given do not work...

The solution always involves EnableEventValidation="false" and override VerifyRenderingInServerForm but these are only available on a Page, not on a Control (what the ascx is).

When changing the ascx to an aspx, the following code fails: page.LoadControl("mycontrol.ascx/aspx") and rendering an aspx is apparently not so easy according to this question.

The Question
How can I render my ascx without the exception?

Bonus question:
Why is EnableEventValidation not available on a Control while there are many examples on the net that claim otherwise? (StackOverflow, CodeProject, ...)

Community
  • 1
  • 1
Laoujin
  • 9,962
  • 7
  • 42
  • 69

1 Answers1

2

I found the solution:

var page = new System.Web.UI.Page();

// Or RenderControl throws 'RegisterForEventValidation can only be called during Render'
page.EnableEventValidation = false; 

// Or generates a second hidden field with ID=_VIEWSTATE
page.EnableViewState = false; 
var sb = new StringBuilder();

var ctl = (SomeAscx)page.LoadControl("SomeAscx.ascx");
using (var sw = new StringWriter(sb))
using (var htw = new HtmlTextWriter(sw))
{
     ctl.RenderControl(htw);
}

string result = sb.ToString();

Key was setting:

page.EnableEventValidation = false; 
page.EnableViewState = false; 
Laoujin
  • 9,962
  • 7
  • 42
  • 69