Client script from ASP.NET Web Forms: alerts, confirms, redirects, refresh and page methods
A Web Forms page lives in two places. The server builds the HTML and handles postbacks; the browser shows dialogs, runs timers and reacts to clicks. Most of the small "how do I…" questions about Web Forms are really about the hand-over between the two: how the server asks the browser to show a message, how the browser asks the server for data without a postback, how a click leads to another page. This guide puts all those hand-overs on one page, with the same three rules throughout: encode every value that crosses from C# to JavaScript, register scripts through the page rather than writing them into the response, and prefer plain HTML (a link, a status message, a panel) whenever it does the job.
Which technique for which need
| You want to… | Use | Section |
|---|---|---|
| Show "Saved" after a postback | An in-page status message, or RegisterStartupScript with an encoded alert() | Alerts |
| Ask "Are you sure?" before a postback | OnClientClick with confirm() | Confirms |
| Run your own JavaScript function after server code | ClientScript or ScriptManager.RegisterStartupScript | Calling JavaScript |
| Send the user elsewhere after a few seconds | A countdown script with a visible link | Timed redirects |
| Keep a dashboard up to date | Timer + UpdatePanel, or fetch of JSON | Auto-refresh |
| Go to another page when a button is clicked | A link, Response.Redirect or PostBackUrl | Button redirects |
| Stop double orders from double clicks | UseSubmitBehavior="false" or a submit handler, plus a server check | Double submits |
| Get data from the server without a postback | A [WebMethod] page method called with jQuery | Page methods |
| Have several submit buttons in one MVC form | A named button value, formaction or a selector attribute | MVC buttons |
Alerts from code-behind
The most frequent request comes first: a message after the server has done its work.
"Record saved" in a browser alert box after a button click is a common request. The server cannot open a dialog itself; it writes a small script that the browser runs when the page comes back. Done properly, the message is encoded, the script runs after the page has loaded and it works inside UpdatePanels.

A reusable helper
using System.Web;
using System.Web.UI;
public static class PageExtensions
{
public static void Alert(this Page page, string message)
{
// JavaScriptStringEncode(…, true) adds the quotes and escapes ', ", \, line breaks and </script>
string script = "alert(" + HttpUtility.JavaScriptStringEncode(message, true) + ");";
// Works for full postbacks and for asynchronous postbacks (needs a ScriptManager for the latter)
if (ScriptManager.GetCurrent(page) != null)
ScriptManager.RegisterStartupScript(page, page.GetType(), "alert", script, true);
else
page.ClientScript.RegisterStartupScript(page.GetType(), "alert", script, true);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (!IsValid) return;
Save();
this.Alert("Record saved for " + txtName.Text + ".");
}
The encoding matters even for messages you write yourself, because they often contain user input such as a name. Without it, an apostrophe in "O'Brien" ends the string and the script fails; a crafted value could run arbitrary script.
Why not Response.Write?
// Avoid
Response.Write("<script>alert('Saved');</script>");
Response.Write during an event handler writes before the <!DOCTYPE> and <html> tags. Browsers switch to quirks mode, layouts break, and inside an UpdatePanel it corrupts the partial-page response with a parsing error. RegisterStartupScript places the script at the end of the form instead.
Alert then redirect
string script = "alert(" + HttpUtility.JavaScriptStringEncode("Order placed.", true) + ");" +
"window.location = " + HttpUtility.JavaScriptStringEncode(ResolveUrl("~/Orders.aspx"), true) + ";";
ClientScript.RegisterStartupScript(GetType(), "done", script, true);
Do not combine this with Response.Redirect in the same request: the redirect happens on the server first and the script never reaches the browser.
The better alternative: an in-page message
alert() blocks the page, cannot be styled, and some browsers let users suppress repeated dialogs. A message rendered in the page is clearer and accessible:
<div role="status" class="notice">
<asp:Literal ID="litStatus" runat="server" Mode="Encode" />
</div>
litStatus.Text = "Record saved for " + txtName.Text + ".";
With role="status", screen readers announce the text when it appears after an UpdatePanel refresh. Keep alerts for rare, blocking warnings.
More on running scripts from the server: Call a JavaScript function from code-behind. Asking the user to confirm instead: Show a confirm box.
Confirm boxes, on the client and on the server
A confirmation is the same mechanism in the other direction: the browser decides whether the postback happens at all.
The browser's confirm() dialog returns true or false. Returning that value from a button's client-side click handler is enough to cancel a postback when the user clicks Cancel. The more delicate case is when the server must decide whether to ask, for example "this customer has open orders, delete anyway?".

Confirm before posting back
<asp:Button ID="btnDelete" runat="server" Text="Delete account"
OnClick="btnDelete_Click"
OnClientClick="return confirm('Delete this account? This cannot be undone.');" />
ASP.NET renders onclick="return confirm(…);" before its own postback code. If the user cancels, the function returns false and the submit stops. With UseSubmitBehavior="false" or a LinkButton, the same pattern works because ASP.NET appends its __doPostBack call after your script.
Watch out for client-side validators: returning true explicitly would skip ASP.NET's validation script in some configurations. Write if (!confirm('…')) return false; rather than return confirm('…'); when validators share the button.
Message set from code-behind
protected void Page_Load(object sender, EventArgs e)
{
string msg = "Delete the account of " + CurrentCustomer.Name + "?";
btnDelete.OnClientClick = "if (!confirm(" + HttpUtility.JavaScriptStringEncode(msg, true) + ")) return false;";
}
Encoding the message prevents a name containing quotes from breaking the script, or worse.
In GridView rows
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="Delete" Text="Delete"
OnClientClick='<%# "if (!confirm(" + HttpUtility.JavaScriptStringEncode("Delete " + Eval("Name") + "?", true) + ")) return false;" %>' />
</ItemTemplate>
</asp:TemplateField>
Add <%@ Import Namespace="System.Web" %> if HttpUtility is not recognised in the markup.
When the server decides whether to ask
Sometimes the need to confirm is only known after checking the database. Use two steps: the first postback checks, and if confirmation is needed, the page shows a question; a second button performs the action.
<asp:Button ID="btnDelete" runat="server" Text="Delete customer" OnClick="btnDelete_Click" />
<asp:Panel ID="pnlConfirm" runat="server" Visible="false" CssClass="confirm" role="alertdialog" aria-labelledby="confirmText">
<p id="confirmText"><asp:Literal ID="litConfirm" runat="server" Mode="Encode" /></p>
<asp:Button ID="btnConfirmDelete" runat="server" Text="Yes, delete" OnClick="btnConfirmDelete_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
</asp:Panel>
protected void btnDelete_Click(object sender, EventArgs e)
{
int open = OrderRepository.CountOpen(CustomerId);
if (open == 0) { DeleteCustomer(); return; }
litConfirm.Text = $"This customer has {open} open order(s). Delete anyway?";
pnlConfirm.Visible = true;
}
protected void btnConfirmDelete_Click(object sender, EventArgs e)
{
DeleteCustomer(); // re-check permissions here: this is a separate request
pnlConfirm.Visible = false;
}
protected void btnCancel_Click(object sender, EventArgs e) => pnlConfirm.Visible = false;
This approach needs no script, works with keyboard and screen readers, and keeps the decision on the server. A <dialog> element or a modal from your UI library can present the panel more attractively.
Showing a simple information message is covered in Show an alert from code-behind.
Calling any JavaScript function from code-behind
Alerts and confirms are special cases of a general pattern: the server registers a script that calls a function already present in the page.
Server code cannot call a browser function directly: by the time the browser runs any script, the server has finished. What the server can do is write a script into the response that calls the function when the page loads. Web Forms has two helpers for that, and the important detail is encoding the values you pass.
Full postback: ClientScript.RegisterStartupScript
<script>
function showSaved(name, count) {
document.getElementById("status").textContent = name + " saved (" + count + " items).";
}
</script>
<p id="status" role="status"></p>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
protected void btnSave_Click(object sender, EventArgs e)
{
string name = txtListName.Text;
int count = SaveList();
var json = new System.Web.Script.Serialization.JavaScriptSerializer();
string script = "showSaved(" + json.Serialize(name) + ", " + count + ");";
ClientScript.RegisterStartupScript(GetType(), "saved", script, true);
}
- The script is emitted just before the closing
</form>tag, so the elements of the form exist when it runs. - The key (
"saved") prevents the same script being registered twice in one response. trueas the last argument wraps the code in<script>tags.JavaScriptSerializer.Serializeturns the string into a JavaScript string literal with quotes, backslashes and line breaks escaped. Never concatenate raw user text into script, e.g."showSaved('" + name + "')": a name containing a quote breaks the script, and a malicious one injects code.HttpUtility.JavaScriptStringEncode(name, true)is an equivalent option.
Inside an UpdatePanel: ScriptManager.RegisterStartupScript
After an asynchronous postback, scripts registered through ClientScript are not executed, because only the panel's HTML is updated. Register through the ScriptManager with the control that caused the update:
ScriptManager.RegisterStartupScript(btnSave, btnSave.GetType(), "saved", script, true);
This overload works for full and partial postbacks, so code that might run in both situations can always use it (the page needs a ScriptManager).
A cleaner alternative: render data, let the script react
Generated script is hard to test and conflicts with a Content Security Policy that blocks inline scripts. Rendering a value and letting a static script read it avoids both:
<asp:Panel ID="pnlNotice" runat="server" CssClass="notice" Visible="false" data-autohide="5000">
<asp:Literal ID="litNotice" runat="server" Mode="Encode" />
</asp:Panel>
litNotice.Text = name + " saved."; // Mode="Encode" HTML-encodes it
pnlNotice.Visible = true;
// site.js, loaded on every page
document.querySelectorAll("[data-autohide]").forEach(function (el) {
setTimeout(function () { el.hidden = true; }, Number(el.dataset.autohide));
});
Alerts and confirmations from the server have their own articles: Show an alert from code-behind and Show a confirm box. Calling the server from script is the reverse direction: Call a server-side method with jQuery AJAX.
Redirecting after a few seconds
A timed redirect is a startup script with a delay, but HTTP and HTML also offer declarative versions.
A "you will be redirected in 5 seconds" page is common after a form submission, a logout or when content has moved. There are three ways to do it in an ASP.NET page; the JavaScript version is the friendliest because it can show a countdown and still offers a link.
1. The Refresh header from code-behind
protected void Page_Load(object sender, EventArgs e)
{
// "5; url=..." : wait 5 seconds, then load the URL
Response.AppendHeader("Refresh", "5; url=" + ResolveUrl("~/Default.aspx"));
}
Browsers honour the Refresh header even though it was never part of the HTTP standard; HTML defines the equivalent meta element. Use relative or same-site URLs only. Never put a URL taken from the query string into this header without checking it, or the page becomes an open redirect that attackers can use in phishing links.
2. A meta refresh tag
<head runat="server">
<meta http-equiv="refresh" content="5; url=Default.aspx" />
<title>Thank you</title>
</head>
Or add it from code so the target can vary:
var meta = new HtmlMeta { HttpEquiv = "refresh", Content = "5; url=" + ResolveUrl("~/Orders.aspx") };
Page.Header.Controls.Add(meta);
3. A JavaScript countdown
<p>Your message has been sent. You will be taken to the home page in
<strong id="seconds">5</strong> seconds.</p>
<p><a id="next" href="<%= ResolveUrl("~/Default.aspx") %>">Go now</a></p>
<script>
(function () {
var left = 5;
var counter = document.getElementById("seconds");
var target = document.getElementById("next").href;
var timer = setInterval(function () {
left -= 1;
counter.textContent = left;
if (left <= 0) {
clearInterval(timer);
window.location.assign(target);
}
}, 1000);
})();
</script>
The link works without JavaScript and lets impatient users skip the wait. location.assign keeps the current page in history; use location.replace if the back button should not return to the waiting page.
Showing it after a postback
For a "saved, returning to the list" message, register the script only after a successful save:
protected void btnSave_Click(object sender, EventArgs e)
{
SaveOrder();
pnlForm.Visible = false;
pnlDone.Visible = true; // contains the countdown markup above
}
When not to wait
- Moved pages: send a permanent redirect immediately with
Response.RedirectPermanent(url)(301). Search engines transfer the old URL's signals to the new one; a timed refresh is weaker and confuses users. - After a POST: the Post/Redirect/Get pattern (
Response.Redirectright after saving) prevents duplicate submissions when the user refreshes. - Accessibility: WCAG asks that time limits can be turned off or extended, and recommends against timed redirects (technique F41). A short delay with a visible link is acceptable for confirmation pages; for anything the user needs to read, do not redirect automatically.
Refreshing the same page periodically is a different need, covered in Auto-refresh a page every 10 seconds. Redirecting on a button click is in Redirect on button click.
Refreshing a page or part of it automatically
Refreshing the same page on a schedule uses the same tools as a timed redirect, plus the UpdatePanel for partial updates.
Dashboards, queue monitors and score boards need fresh data without the user pressing F5. Reloading the whole page every ten seconds takes one line; refreshing only the part that changes is smoother and lighter, and Web Forms has a control for exactly that.
Whole page: Refresh header or meta tag
protected void Page_Load(object sender, EventArgs e)
{
Response.AppendHeader("Refresh", "10"); // reload this URL every 10 seconds
}
Or in the markup: <meta http-equiv="refresh" content="10">. Each reload is a fresh GET: the browser re-requests the page, scroll position may reset, and anything typed in a form is lost. It suits wall displays, not pages people interact with.
Part of the page: Timer and UpdatePanel
<asp:ScriptManager ID="sm" runat="server" />
<asp:UpdatePanel ID="upStatus" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Timer ID="tmrRefresh" runat="server" Interval="10000" OnTick="tmrRefresh_Tick" />
<p>Orders waiting: <asp:Label ID="lblWaiting" runat="server" /></p>
<p class="small">Updated <asp:Label ID="lblTime" runat="server" /></p>
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) LoadStatus();
}
protected void tmrRefresh_Tick(object sender, EventArgs e)
{
LoadStatus();
}
private void LoadStatus()
{
lblWaiting.Text = OrderQueue.CountWaiting().ToString();
lblTime.Text = DateTime.Now.ToString("HH:mm:ss");
}
The Timer control's Interval is in milliseconds. Each tick performs an asynchronous postback; because the timer sits inside the panel, only that panel is re-rendered. The rest of the page, including form fields being edited, is untouched.
To refresh a panel from a timer placed elsewhere, register it as a trigger: <Triggers><asp:AsyncPostBackTrigger ControlID="tmrRefresh" EventName="Tick" /></Triggers>. Set tmrRefresh.Enabled = false from code to stop refreshing, for example when a job has finished.
Keep in mind that a partial postback still sends the full form and view state and runs the full page life cycle on the server. On a heavy page, ten-second ticks from many users add up.
A lighter alternative: fetch JSON
When only a number or two change, ask the server for those values alone. A generic handler (Status.ashx) returns JSON:
public class Status : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Write("{\"waiting\":" + OrderQueue.CountWaiting() + "}");
}
public bool IsReusable => true;
}
async function refreshStatus() {
try {
const res = await fetch("Status.ashx", { cache: "no-store" });
if (res.ok) {
const data = await res.json();
document.getElementById("waiting").textContent = data.waiting;
}
} catch (e) { /* network hiccup: try again next time */ }
}
setInterval(refreshStatus, 10000);
Pause polling when the tab is hidden by checking document.visibilityState in the callback; nobody needs updates for a page they are not looking at.
Accessibility
Content that changes on its own can be missed by screen-reader users or disrupt them. Wrap the changing value in a container with aria-live="polite" so updates are announced without interrupting, and provide a way to pause automatic updates if they are more than a small status value (WCAG 2.2.2).
To leave the page for another one after a delay instead, see Redirect after a few seconds.
Redirecting on a button click
When the user decides when to leave, the choice is between a link, a client-side redirect and a server-side redirect after some work.
"Go to page X when the user clicks this button" has several answers in Web Forms. If nothing needs to happen on the server first, the simplest is not a button at all but a link. When the server must work first, redirect from the click handler.
No server work needed: use a link
<asp:HyperLink runat="server" NavigateUrl="~/Orders/New.aspx" CssClass="button" Text="New order" />
A link navigates without script, can be opened in a new tab, and is announced correctly by screen readers. Style it as a button if the design requires.
Client-side redirect from a button
<asp:Button ID="btnHelp" runat="server" Text="Help"
OnClientClick="window.location.assign('Help.aspx'); return false;" />
return false cancels the postback that an asp:Button would otherwise trigger. Build the URL with ResolveUrl("~/Help.aspx") in code if the page may sit in a subfolder.
The same with jQuery, keeping script out of the markup:
$(function () {
$("#<%= btnHelp.ClientID %>").on("click", function (e) {
e.preventDefault();
var term = encodeURIComponent($("#<%= txtSearch.ClientID %>").val());
window.location.href = "Help.aspx?q=" + term;
});
});
location.href = … and location.assign(…) add a history entry; location.replace(…) does not, so the back button skips the current page. To open a new tab: window.open(url, "_blank", "noopener"), called directly in the click handler so popup blockers allow it.
Server-side redirect after work
protected void btnCheckout_Click(object sender, EventArgs e)
{
if (!IsValid) return;
int orderId = CreateOrder();
Response.Redirect("~/Orders/Confirm.aspx?id=" + orderId, false);
Context.ApplicationInstance.CompleteRequest();
}
Redirecting after a successful POST (Post/Redirect/Get) prevents the "resend form data?" prompt and duplicate orders on refresh. The false argument plus CompleteRequest() ends the request without the ThreadAbortException that Response.Redirect(url) uses internally.
Never redirect to a URL taken unchecked from user input (?returnUrl=…): check that it is local, for example with Uri.IsWellFormedUriString(url, UriKind.Relative) and a leading single slash, to avoid an open redirect.
Posting the form to another page
PostBackUrl sends the form itself to another page, which can read the values through PreviousPage: see Cross-page posting. A redirect after a countdown is in Redirect after a delay.
Which one to choose
| Need | Use |
|---|---|
| Plain navigation | HyperLink or <a href> |
| Navigation built from form values, no server work | Client-side location.href |
| Save first, then go elsewhere | Response.Redirect in the click handler |
| Send the whole form to another page | PostBackUrl |
| Page moved permanently | Response.RedirectPermanent (301) |
Preventing double submits
Disabling a button looks like a one-liner, but Web Forms buttons have a trap that silently cancels the postback.
Users double-click buttons, especially when a page is slow. On a payment or order form that means two orders. Disabling the button once the form is on its way prevents most duplicates, but on a Web Forms page there are two traps: a disabled submit button is not posted, so its Click event never fires, and validation may have stopped the submit anyway.
The trap
// Looks right, breaks the server event:
$("#<%= btnOrder.ClientID %>").on("click", function () {
$(this).prop("disabled", true);
});
ASP.NET knows which button was clicked because the browser posts the button's name and value. A button disabled before the form is submitted is not included, so btnOrder_Click silently does nothing.
Solution 1: UseSubmitBehavior="false" (Web Forms)
<asp:Button ID="btnOrder" runat="server" Text="Place order" OnClick="btnOrder_Click"
UseSubmitBehavior="false"
OnClientClick="if (typeof Page_ClientValidate === 'function' && !Page_ClientValidate()) return false; this.disabled = true; this.value = 'Sending…';" />
With UseSubmitBehavior="false", ASP.NET renders a plain button that posts through __doPostBack, which sends the button's identity in the __EVENTTARGET field. Disabling the button no longer loses the event. The script first runs client validation (if validators are on the page) so the button is not disabled for a form that will not be sent.
Solution 2: disable on the form's submit event (jQuery)
$(function () {
$("form").on("submit", function () {
var $form = $(this);
// let validation cancel the submit first
if (typeof Page_IsValid !== "undefined" && !Page_IsValid) return;
// defer so the clicked button's name/value is captured before disabling
setTimeout(function () {
$form.find("input[type=submit], button[type=submit]")
.prop("disabled", true)
.addClass("is-busy");
}, 0);
});
});
The form's submission data is constructed when the submit happens, so disabling the buttons in a zero-delay timeout leaves the clicked button's value in the request. This works for plain HTML forms too. If a validator fails, Web Forms' own script cancels the submit before this handler matters.
With an UpdatePanel, the page is not reloaded after an asynchronous postback, so re-enable the buttons in a Sys.WebForms.PageRequestManager endRequest handler.
The server must still check
Script can be off, a request can be replayed, and two tabs can submit the same order. Make the operation idempotent on the server: generate a unique token when the form is shown (in a hidden field), store it with the order, and reject a second order with the same token, for example with a unique index.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) hfOrderToken.Value = Guid.NewGuid().ToString("N");
}
protected void btnOrder_Click(object sender, EventArgs e)
{
if (!Guid.TryParseExact(hfOrderToken.Value, "N", out Guid token)) return;
bool created = OrderService.TryCreate(token, ReadOrderFromForm()); // unique index on token
lblResult.Text = created ? "Order placed." : "This order was already received.";
}
A related helper is enabling and disabling a TextBox from a button.
Calling server code from jQuery: page methods
This is the reverse direction: the browser asks the server for data and the page is not posted back.
A Web Forms page can expose a static method marked [WebMethod], called a page method. jQuery can call it with a JSON POST and get a JSON result back, without a postback, view state or page life cycle. It is a lightweight way to add a lookup, a check or a small save operation to an existing page.
The server side
using System.Web.Services;
public partial class Stock : Page
{
[WebMethod]
public static StockInfo GetStock(int productId)
{
if (productId <= 0) throw new ArgumentOutOfRangeException(nameof(productId));
int qty = InventoryRepository.Quantity(productId);
return new StockInfo { ProductId = productId, Quantity = qty, Checked = DateTime.UtcNow.ToString("o") };
}
}
public class StockInfo
{
public int ProductId { get; set; }
public int Quantity { get; set; }
public string Checked { get; set; }
}
Page methods must be public static. They have no access to the page's controls (no instance exists), but HttpContext.Current gives you the request, the user and, if enabled with [WebMethod(EnableSession = true)], the session.
The jQuery call
<input type="number" id="productId" value="42" min="1">
<button type="button" id="check">Check stock</button>
<output id="result"></output>
<script>
$("#check").on("click", function () {
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/Stock.aspx/GetStock") %>",
data: JSON.stringify({ productId: parseInt($("#productId").val(), 10) }),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (res) {
var info = res.d; // ASP.NET wraps the result in a "d" property
$("#result").text(info.Quantity + " in stock");
}).fail(function (xhr) {
var msg = (xhr.responseJSON && xhr.responseJSON.Message) || xhr.statusText;
$("#result").text("Error: " + msg);
});
});
</script>
- The URL is the page followed by
/MethodName. - The request must be a POST with
contentType: "application/json"; otherwise ASP.NET returns the page HTML or an error. - The JSON property names must match the C# parameter names.
- The
dwrapper exists for security reasons (it prevents a JSON array from being executed as a script); readres.d. - Dates in
DateTimeproperties arrive as/Date(…)/; returning an ISO string, as above, is simpler. See Parse JSON dates.
Projects created from the Web Forms template with FriendlyUrls may redirect Stock.aspx to Stock, which breaks the POST. Use ~/Stock.aspx/GetStock and, if necessary, set settings.AutoRedirectMode = RedirectMode.Off in RouteConfig.
Security
A page method is a public endpoint. Check authorisation inside it (HttpContext.Current.User.Identity.IsAuthenticated, roles), validate every argument, and for methods that change data, protect against cross-site request forgery: the JSON content type is not a reliable defence on its own. Return only the data needed, never stack traces; in production, the error message in the response is generic when customErrors is on.
Alternatives
For several endpoints, a generic handler (.ashx), an ASMX service, or ASP.NET Web API in the same project gives cleaner URLs and better control of serialisation. In new projects on ASP.NET Core, minimal APIs fill this role. Calling script from the server is the reverse topic: Call JavaScript from code-behind.
Several submit buttons in one ASP.NET MVC form
MVC has no server-side click events, so the question "which button was pressed?" needs its own answer.
An edit form with Save draft and Publish, or a wizard with Back and Next, has several submit buttons in one <form>. In Web Forms each button gets its own event handler; in MVC the form posts to one URL, so the action has to find out which button was used.
1. Name the buttons and bind the value
A submit button with a name sends its name=value pair, and only the clicked button does so:
@model ArticleEditModel
@using (Html.BeginForm("Edit", "Articles", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.Id)
@Html.EditorFor(m => m.Title)
@Html.TextAreaFor(m => m.Body)
<button type="submit" name="command" value="draft">Save draft</button>
<button type="submit" name="command" value="publish">Publish</button>
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ArticleEditModel model, string command)
{
if (!ModelState.IsValid) return View(model);
switch (command)
{
case "publish":
_articles.Publish(model);
return RedirectToAction("Details", new { id = model.Id });
case "draft":
_articles.SaveDraft(model);
TempData["Message"] = "Draft saved.";
return RedirectToAction("Edit", new { id = model.Id });
default:
return new HttpStatusCodeResult(400); // unknown or missing button
}
}
Use <button> with a separate value rather than <input type="submit" value="Publish">: the label can then change or be translated without breaking the code. If the user submits by pressing Enter in a text field, browsers use the first submit button in the form as the "clicked" one, so put the safest action first.
2. One action per button with formaction
HTML5's formaction attribute sends the form to a different URL depending on the button:
<button type="submit" formaction="@Url.Action("SaveDraft", "Articles")">Save draft</button>
<button type="submit" formaction="@Url.Action("Publish", "Articles")">Publish</button>
[HttpPost, ValidateAntiForgeryToken]
public ActionResult SaveDraft(ArticleEditModel model) { /* ... */ }
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Publish(ArticleEditModel model) { /* ... */ }
Each action stays small and has its own authorisation attributes, which is useful when only editors may publish. formnovalidate on a button (for example Cancel) skips the browser's built-in validation for that button only.
3. A selector attribute
For many forms with the same pattern, an ActionNameSelectorAttribute picks the action whose name matches the posted button name:
public class SubmitButtonAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext context, string actionName, MethodInfo methodInfo)
{
return context.HttpContext.Request.Form["action:" + methodInfo.Name] != null;
}
}
// View: <button type="submit" name="action:Publish">Publish</button>
[HttpPost, ValidateAntiForgeryToken, SubmitButton, ActionName("Edit")]
public ActionResult Publish(ArticleEditModel model) { /* ... */ }
This is clever but less obvious to the next developer; the first two options are usually enough.
Validation per button
Server-side validation runs on the bound model whatever the button. If a draft may be incomplete while publishing requires every field, validate conditionally: remove errors for optional fields with ModelState.Remove("Body") in the draft branch, or use separate view models per action with option 2.
ASP.NET Core
The same three approaches work in ASP.NET Core MVC. Razor Pages adds named handlers: <button asp-page-handler="Publish"> calls OnPostPublishAsync. The programming models are compared in The three ASP.NET programming models.
Checklist before you ship
- Every value written into a script goes through
HttpUtility.JavaScriptStringEncode(value, true)or a JSON serializer, never plain concatenation. - Scripts are registered with
ScriptManager.RegisterStartupScriptwhen the page has aScriptManager, so they also run after partial postbacks. - No
Response.Writeof script tags, and noResponse.Redirectin the same request as a script you expect to run. - Redirect targets come from your own code or an allow-list, never straight from the query string.
- Anything decided in the browser (a confirmation, a disabled button) is checked again on the server.
- Messages that matter are also rendered in the page with
role="status", so screen-reader users hear them.
Sources
- Microsoft Learn: ScriptManager.RegisterStartupScript, HttpUtility.JavaScriptStringEncode, Button.OnClientClick, ClientScriptManager.RegisterStartupScript, HttpResponse.RedirectPermanent, HtmlMeta.HttpEquiv, Timer class (System.Web.UI), UpdatePanel, HttpResponse.Redirect, Button.PostBackUrl, Button.UseSubmitBehavior, WebMethodAttribute, ActionNameSelectorAttribute, Razor Pages in ASP.NET Core (named handler methods).
- MDN: Window.alert(), ARIA status role, Window.confirm(), <dialog>, <meta http-equiv>, Location.assign(), Fetch API, Document.visibilityState, aria-live, Location.replace(), Window.open(), HTMLFormElement: submit event, <button>.
- jQuery API: submit event, .prop(), jQuery.ajax(), deferred.done().
- OWASP: Unvalidated Redirects and Forwards Cheat Sheet, CSRF Prevention Cheat Sheet.
- W3C: WCAG failure F41: using meta refresh to reload or redirect, Understanding SC 2.2.2 Pause, Stop, Hide.