If you are staying on the same page, clearing it on the client-side or from the code-behind on the postback would be slightly preferable to a redirect, as you are saving a trip to the server, although it will take more work.
Also, Response.Redirect(url)
throws a ThreadAbortionException
, which has a negative effect on performance, so if you want to go the redirect route, consider Response.Redirect(url, false)
.
Client-side option: (the easy way)
<script>
$(':input').each(function () {
switch (this.type) {
case 'password':
case 'text':
case 'select-multiple':
case 'select-one':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
break;
}
});
</script>
Code pilfered from this post.
Server-side option:
You could loop through all the controls to clear them out. At the end of the function that processes your form, add:
ClearForm(Page.Form.Controls);
The function:
public void ClearForm(ControlCollection controls)
{
foreach (Control c in controls)
{
if (c.GetType() == typeof(System.Web.UI.WebControls.TextBox))
{
System.Web.UI.WebControls.TextBox t = (System.Web.UI.WebControls.TextBox)c;
t.Text = String.Empty;
}
//... test for other controls in your forms DDL, checkboxes, etc.
if (c.Controls.Count > 0) ClearForm(c.Controls);
}
}
Looping through Controls and child controls is something that comes up a lot, so you could write an extension method to do this. Something along the lines of what I did in this post (but instead a function that instead returns a collection of all the Controls). I have an extension method in my project that does this, called GetAllChildren(), so the same code above would be executed like this:
foreach (Control i in Page.Form.GetAllChildren())
{
if (i.GetType() == typeof(System.Web.UI.WebControls.TextBox))
{
System.Web.UI.WebControls.TextBox t = (System.Web.UI.WebControls.TextBox)i;
t.Text = String.Empty;
}
// check other types
}