在Url重写的页面中进行PostBack并且不跳转的情况,会导致URL变回URL重写前的原始URL,这样的体验不太好,但是这种请况可以通过重写
protected override void Render(HtmlTextWriter writer)方法来修正这种问题。
考虑到Render方法中的HtmlTextWriter也有可能是来源于它的继承类Html32TextWriter,所以这里做了两个继承类分别处理这两种情况。
FormFixerHtml32TextWriter
public class FormFixerHtml32TextWriter : System.Web.UI.Html32TextWriter
{
private string _url;
public FormFixerHtml32TextWriter(TextWriter writer)
: base(writer)
{
_url = HttpContext.Current.Request.RawUrl;
}
public override void WriteAttribute(string name, string value, bool encode)
{
if (_url != null && string.Compare(name, "action", true) == 0)
{
value = _url;
}
base.WriteAttribute(name, value, encode);
}
}
FormFixerHtmlTextWriter
public class FormFixerHtmlTextWriter : System.Web.UI.HtmlTextWriter
{
private string _url;
public FormFixerHtmlTextWriter(TextWriter writer)
: base(writer)
{
_url = HttpContext.Current.Request.RawUrl;
}
public override void WriteAttribute(string name, string value, bool encode)
{
if (_url != null && string.Compare(name, "action", true) == 0)
{
value = _url;
}
base.WriteAttribute(name, value, encode);
}
}
随后创建一个助手方法(当然也可以用基页面的方式,通过继承实现)
PageHelper
public static class PageHelper
{
public static HtmlTextWriter Render(HtmlTextWriter writer)
{
if (writer is System.Web.UI.Html32TextWriter)
{
writer = new FormFixerHtml32TextWriter(writer.InnerWriter);
}
else
{
writer = new FormFixerHtmlTextWriter(writer.InnerWriter);
}
return writer;
}
}
在需要实现这种postback的页面中重写protected override void Render(HtmlTextWriter writer)方法,例如:
Render
protected override void Render(HtmlTextWriter writer)
{
base.Render(PageHelper.Render(writer));
}
通过页面继承基类,在基类中统一处理这样的问题也是可以的。