Reset Form fields data after form submit PostBack in ASP.Net

How Reset Form fields data after form submit PostBack in ASP.Net?

by Form fields can be reset by setting each field to its default value but this process could be tedious when there are too many fields in the form



The following HTML Markup consists of a standard form with some fields and a Button to submit the form and insert the data into database.

<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
Name:
</td>
<td>
<asp:TextBox ID="txtName" runat="server" />
</td>
</tr>
<tr>
<td>
City:
</td>
<td>
<asp:TextBox ID="txtCity" runat="server" />
</td>
</tr>
<tr>
<td>
Country:
</td>
<td>
<asp:TextBox ID="txtCountry" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSave" Text="Save" runat="server" OnClick="Save" />
</td>
</tr>
</table>
 
 
On Reset Button:
 
When the Submit Button is clicked, first the record is inserted into the database and then using ClientScript RegisterStartupScript function, the success message is displayed in JavaScript alert message box.
message – The message to be displayed in the JavaScript Alert Message Box.
script – The JavaScript code that will display the Alert message box.
Once the OK button of the JavaScript Alert Message Box is clicked, the form fields (data) is cleared (reset) by redirecting to the same page using JavaScript window.location function. 
 
protected void Save(object sender, EventArgs e)
{
//Insert record here.

//Display success message and clear the form.
string message = "Your details have been saved successfully.";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
 

No comments:

Post a Comment