Here is an example I recently created as part of a testing application.
To begin, I utilized the ScriptManager to incorporate specific javascript files for the webpage:
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/JS/tester.js" />
</Scripts>
</asp:ScriptManager>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Call database" />
</div>
</form>
</body>
You can add more JS files inside the <Scripts>
tag to ensure they are loaded with the webpage.
The content of my tester.js file includes:
function alertbox(data) {
alert("Completed the database operation with following data = " + data);
}
In the code-behind, I have set up a button on the webpage that performs database operations and alerts the user once completed:
protected void Button1_Click(object sender, EventArgs e)
{
Thread.Sleep(2000);
int sqlReturnValue = ExecuteTheQuery();
ScriptManager.RegisterStartupScript(this, typeof(string), "Database Completed", "alertbox(" + sqlReturnValue + ");", true);
}
This will trigger the Javascript function alertbox.
(Please note, this example demonstrates achieving a specific task)
Update:
A similar outcome can also be achieved using ClientScript. Add a script tag in the head section:
<head runat="server">
<title>Test Page</title>
<script src="JS/tester.js" type="text/javascript"></script>
</head>
In the button click code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
Thread.Sleep(2000);
ClientScript.RegisterStartupScript(this.GetType(), "Database Completed", "alertbox(23);", true);
}
For further understanding of ClientScript and ScriptManager, refer to this question.