Because ASP.NET uses postback procedures when a user clicks a button, you can't simply insert Javascript functions into the web page's code. The Javascript must be declared in the code-behind in the application. Using C#, this example shows programmers how to create a confirmation window when users delete a record.
Instructions:
1) Create a button. A button is needed to link the Javascript code. The button is placed in between the page's form tags. For example, the code below places a new ASP button.
2)Insert the Javascript confirmation code in the Page_Load function. The Page_Load function is called at the beginning of every instance of the webpage. When the page is loaded in the user's browser, this function is called. Code that needs to be run during the web page's load process is placed in this function. Below is an example of Javascript loaded into the button created in Step 1. It creates a confirmation screen that verifies the user's deletion.
protected void Page_Load(object sender, EventArgs e){
btnDelete.Attributes.Add("onClick",
"return confirm('Do you want to delete this record?');");
}
3) Create Javascript functions. You may want to place a Javascript function on your page. In older web programming languages, the code is placed on the page and called when specified on the web page controls. However, with ASP.NET, the Javascript functions need to be registered before they will work. Here is an example of creating a Javascript function on an ASP.NET webpage.
using System.Text;
StringBuilder myString = new StringBuilder();
sb.Append("")
// Register the code with the ASP.NET page
Page.RegisterStartupScript("AlertScript", myString.ToString());
4) Test the code. Open the new webpage in your browser. If no syntax errors are present, the page will open and show a button with the text "Delete Record."
5)Click the new button. If the code was inserted properly, a confirmation screen should appear asking if you want to delete the record. If you hit "Cancel," it should cancel the operation. Clicking "OK" continues with the deletion process.