RegisterForEventValidation只能在渲染期间调用

我有一个web方法,将从jquery ajax调用:

[WebMethod] public string TestMethod(string param1, string param2) { StringBuilder b = new StringBuilder(); HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b)); this.LoadControl("~/Pages/Controls/Listing.ascx").RenderControl(h); string controlAsString = b.ToString(); return controlAsString; } 

(这是一种非静态的方法,我们能够击中它。这不是问题)

执行loadControl()方法时,我收到一条错误消息:只能在Render期间调用RegisterForEventValidation。

我已经为当前的aspx,禁用的viewstate包含了EnableEventValidation =“false”。 但我仍然得到同样的错误。 有什么想法吗?

解决方案是禁用Page的事件validation

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

并通过在C#代码后面添加以下方法来覆盖VerifyRenderingInServerForm

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

请参阅下面的链接

http://www.codeproject.com/Questions/45450/RegisterForEventValidation-can-only-be-called-duri

根据Brian的第二个链接,没有进一步跳跃,只需这样做:

 StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); Html32TextWriter hw = new Html32TextWriter(sw); Page page = new Page(); HtmlForm f = new HtmlForm(); page.Controls.Add(f); f.Controls.Add(ctrl); // ctrl.RenderControl(hw); // above line will raise "RegisterForEventValidation can only be called during Render();" HttpContext.Current.Server.Execute(page, sw, true); Response.Write(sb);