Is there an easy way to reset all the fields in a form?
I have around 100 controls in my asp.net form and there are submit and reset buttons.
How do I make a
Loop through all of the controls on the page, and if the control is type TextBox, set the Text property to String.Empty
protected void ClearTextBoxes(Control p1)
{
foreach (Control ctrl in p1.Controls)
{
if(ctrl is TextBox)
{
TextBox t = ctrl as TextBox;
if(t != null)
{
t.Text = String.Empty;
}
}
else
{
if (ctrl.Controls.Count > 0)
{
ClearTextBoxes(ctrl);
}
}
}
}
Then to call it in your click event like this:
ClearTextBoxes(Page);
If you are using asp.net formview object, just use myFormView.DataBind();
in your reset button click event.
Or if you are using Angular.
Add this to your button on the cshtml page:
<input type="button" value="Cancel" id="cancel" ng-click="cancel();" />
And this to your .js file:
$scope.cancel = function () {
if (!$('form').dirtyForms('isDirty')) {
$('form').dirtyForms('setClean');
}
else {
$('form').dirtyForms('isDirty', true);
}
var that = this;
var method = that.getUrl('CONTROLLER', 'ACTION', 'id', 'querystring');
window.location = method;
Add this to the server-side handler of the cancel button:
Response.Redirect("~/mypage.aspx", false);
Try adding an:
<input type="reset" value="Clear" />
to your form.
The best option from my side would be
Response.Redirect(Request.RawUrl);
Just add this code on the cancel or reset button of your asp.net control.