Register client script correctly in a Web Forms page

Keep reusable browser functions in an ordinary JavaScript file. Register only the short invocation that must run after a server action.

In a Web Forms page using partial rendering, use ScriptManager.RegisterStartupScript so the invocation is included in the asynchronous response. This procedure targets .NET Framework maintenance applications.

Add a reusable function

In an existing Web Forms application, create Scripts/page.js:

JavaScript
function showSaved() {
  document.getElementById("clientStatus").textContent = "Saved";
}

Inside the page's server form, include one ScriptManager with a script reference, an UpdatePanel and a button:

HTML
<asp:ScriptManager ID="Scripts" runat="server">
  <Scripts><asp:ScriptReference Path="~/Scripts/page.js" /></Scripts>
</asp:ScriptManager>
<span id="clientStatus">Waiting</span>
<asp:UpdatePanel ID="Panel" runat="server">
  <ContentTemplate>
    <asp:Button ID="Save" runat="server" Text="Save" OnClick="Save_Click" />
  </ContentTemplate>
</asp:UpdatePanel>

Add this method to the page's code-behind class:

C#
protected void Save_Click(object sender, EventArgs e) {
	ScriptManager.RegisterStartupScript(this, GetType(), "saved", "showSaved();", true);
}

Open the page and click Save. The client status changes to Saved after the asynchronous response. The example demonstrates script timing. Add the actual persistence operation before registration in a real save handler.

Use a client-only button when no postback is needed

An ordinary <button type="button" onclick="showSaved()">Preview</button> performs only the browser action. For an existing ASP.NET ImageButton, OnClientClick="showSaved(); return false;" cancels its generated postback. Do not cancel the postback when the server action is required.

For a page without partial rendering, Page.ClientScript.RegisterStartupScript is the corresponding full-page mechanism. Never concatenate unescaped user input into JavaScript. Serialize data or use a correctly escaped data attribute and read it from the external script.

Official references

ScriptManager.RegisterStartupScript Method (System.Web.UI)
Registers a startup script block with the ScriptManager control and adds the script block to the page.
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.scriptmanager.registerstartupscript?view=netframework-4.8.1
ScriptManager.RegisterStartupScript

Author: Herman Schoenfeld