Bill Robertson's Blog

How to override the "action" attribute of an Html Form.

Recently I needed to be able to change the action attribute of the form property.  First, I overrode the RenderAttribute method of HtmlForm.

protected override void RenderAttributes( HtmlTextWriter writer )
{
 base.Attributes.Remove( "action" );
 base.RenderAttributes( writer );
}

This did not work because the HtmlForm's Render method manually places the action attribute directly into the HtmlTextWriter.  I needed to find another way.

I could have used a Response.Filter to change the outgoing html, but I ended up overridding the Render method itself.  Here is the class I used to change the action attribute of the html form element.

First I create my own HtmlTextWriter and its own StringWriter backing stream.  I then allow the base.Render method to be called, but using my own HtmlTextWriter.  I capture the output and perform a RegularExpression replace on the output matching for action="stuff" and will replace 'stuff' with the Action property assigned on the form.  If you use this code snippet, you should remove the extra step of assigning it to the string newHtmlForm and write straight to the real HtmlTextWriter.

public class OverrideActionForm : HtmlForm
{
 private string _Action;

 public string Action
 {
  get { return _Action; }
  set { _Action = value; }
 }

 protected override void Render( HtmlTextWriter writer )
 {
  using ( StringWriter stringWriter = new StringWriter() )
  using ( HtmlTextWriter textWriter = new HtmlTextWriter( stringWriter ) )
  {
   base.Render( textWriter );
   string newHtmlForm = Regex.Replace( stringWriter.ToString(), "action=\"[^\"]*\"", "action=\"" + Action + "\"" );
   writer.Write( newHtmlForm ); //finally write out the modified html
  }
 }
}

Posted: Oct 03 2006, 10:52 PM by Bill Robertson | with no comments
Filed under:
Leave a Comment

(required) 

(required) 

(optional)

(required)