asp.net 2.0中的eventvalidation异常处理方法
asp.net 2.0新加入了一个eventValidation的功能。增加了安全性。但如果用户在表单没有完全load的时候就submit了,就会遇到如下错误:
Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
对此,我给出两个解决这一问题的办法:
1 利用javascript在form load 过程中把form隐藏起来。load完成后再显示出来。
<form id="form1" runat="server">
<script type="text/javascript" language="javascript">
var thisForm = window.document.forms[0];
thisForm.style.display="none";
</script>
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
<script type="text/javascript" language="javascript">
thisForm.style.display="";
</script>
2 在server端的c# code里面把__EVENTVALIDATION tag移动到form的开始tag后面,使得__EVENTVALIDATION在所有submit按钮之前load,保证浏览器不会提交没有__EVENTVALIDATION的表单。
具体的做法是重载了页面的Render方法,用正则表达式提取__EVENTVALIDATION标记,然后插入到form的开始标记后面。
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sbRenderedHtml = new StringBuilder();
StringWriter strWriter = new StringWriter(sbRenderedHtml);
HtmlTextWriter htWriter = new HtmlTextWriter(strWriter);
base.Render(htWriter);
string renderedHtml = sbRenderedHtml.ToString();
Regex reg = new Regex("^(?<formHead>.*?<\\s*form(\\s+.*?>)|>)(?<formBody>.*(?=<div>.*?__EVENTVALIDATION.*?</div>))(?<eventValidation><div>.*?__EVENTVALIDATION.*?</div>)(?<formTail>.*)$", RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (reg.IsMatch(renderedHtml))
{
string fixedHtml = Regex.Replace(renderedHtml, "^(?<formHead>.*?<\\s*form(\\s+.*?>)|>)(?<formBody>.*(?=<div>.*?__EVENTVALIDATION.*?</div>))(?<eventValidation><div>.*?__EVENTVALIDATION.*?</div>)(?<formTail>.*)$", "${formHead}${eventValidation}${formBody}${formTail}", RegexOptions.Singleline | RegexOptions.IgnoreCase);
writer.Write(fixedHtml);
}
else
{
writer.Write(renderedHtml);
}
}