ASP.NET WebForms 雖屬經典模式,但在大量存量專案中仍佔主流。本文彙總 25 個高頻實用技巧,涵蓋彈窗傳參、確認對話框、GridView 交互、日期/數字格式化、全局變量、異常處理、腳本技巧等,附可直接複製的代碼片段,作為開發手邊速查手冊。
// 服務端打開新窗口
Response.Write("<script>window.open('Detail.aspx?id=" + ddl.SelectedValue + "')</script>");
// 接收端
string id = Request.QueryString["id"];
// 簡單版
btnDelete.Attributes["onclick"] = "return confirm('確定刪除?');";
// 完整邏輯版
btnDelete.Attributes["onclick"] = "if(confirm('確定?')){return true;}else{return false;}";
// 獲取 DataKey
int id = (int)gv.DataKeys[e.RowIndex].Value;
string sql = "DELETE FROM T WHERE Id=" + id;
// RowCreated 中綁定確認
LinkButton lb = (LinkButton)e.Row.Cells[5].Controls[0];
lb.Attributes["onclick"] = "return confirm('確定刪除此行?');";
// RowDataBound 中綁定
e.Row.Attributes["onclick"] = "window.open('Edit.aspx?id=" + e.Row.Cells[0].Text + "');";
// 雙擊
e.Row.Attributes["ondblclick"] = "location.href='Edit.aspx?id=" + e.Row.Cells[0].Text + "';";
⚠️ URL 參數嚴禁空格:?id=1✅ |?id = 1❌
<asp:HyperLinkColumn Target="_blank"
DataTextField="Title"
DataNavigateUrlFields="Id"
DataNavigateUrlFormatString="Detail.aspx?id={0}" />
// 點擊變色
e.Row.Attributes["onclick"] = "this.style.background='#99cc00';this.style.color='white';";
// 懸停變色
e.Row.Attributes["onmouseover"] = "this.style.background='#eef';";
e.Row.Attributes["onmouseout"] = "this.style.background='';";
// GridView BoundField
DataFormatString="{0:yyyy-MM-dd}" HtmlEncode="false"
// 代碼中
lbl.Text = dt.Rows[0]["CreateTime"].ToString("yyyy-MM-dd");
// Global.asax
protected void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError();
if (ex is HttpUnhandledException)
Server.Transfer("~/Error.aspx"); // 保留異常上下文
// 其他異常交給 ASP.NET 默認處理
}
✅ Server.Transfer 保留堆疊信息,Response.Redirect 會丟失。
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
public class AppException : ApplicationException
{
public AppException(string msg) { EventLog.WriteEntry("MyApp", msg, EventLogEntryType.Error); }
}
// 使用
throw new AppException("庫存不足");
<asp:Panel Style="overflow-x:auto; overflow-y:auto; max-height:400px;">...</asp:Panel>
<script>
document.onkeydown = function(e) {
if (e.keyCode === 13 && !['button','submit','reset','textarea'].includes(e.target.type))
e.keyCode = 9;
};
</script>
DataNavigateUrlFields="Id" DataNavigateUrlFormatString="Edit.aspx?id={0}"
e.Item.Attributes["onmouseover"] = "this.style.background='#EFF3F7';";
e.Item.Attributes["onmouseout"] = "this.style.background='" + e.Item.Style["BACKGROUND-COLOR"] + "';"
<asp:TemplateColumn HeaderText="選中">
<ItemTemplate><asp:CheckBox ID="chk" runat="server" /></ItemTemplate>
<HeaderTemplate><asp:CheckBox ID="chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkAll_CheckedChanged" /></HeaderTemplate>
</asp:TemplateColumn>
// 後台全選邏輯
foreach (DataGridItem item in dg.Items)
((CheckBox)item.FindControl("chk")).Checked = chkAll.Checked;
<%# Eval("Price", "{0:¥#,##0.00}") %>
// 代碼中
price.ToString("N2"); // 1,234.56
// 簡化版:yyyy-MM-dd 或 yyyy/MM/dd
^\d{4}[-/](0[1-9]|1[0-2])[-/](0[1-9]|[12]\d|3[01])$
// Global.asax
Application["AppStartTime"] = DateTime.Now;
// 讀取
var start = (DateTime)Application["AppStartTime"];
<MenuItem ... UrlTarget="_blank" />
foreach (GridViewRow row in gv.Rows)
{
var txt = (TextBox)row.FindControl("txtQty");
// ...
}
<asp:TextBox ID="txtQty" runat="server" onkeyup="calc(this)" />
<asp:TextBox ID="txtPrice" runat="server" onkeyup="calc(this)" />
<asp:TextBox ID="txtAmount" runat="server" ReadOnly="true" />
<script>
function calc(el) {
var row = el.closest('tr');
var q = parseFloat(row.querySelector('[id$=txtQty]').value) || 0;
var p = parseFloat(row.querySelector('[id$=txtPrice]').value) || 0;
row.querySelector('[id$=txtAmount]').value = (q * p).toFixed(2);
}
</script>
// Page_Load
Page.SmartNavigation = true; // 僅 IE 支援,現代瀏覽器請用 UpdatePanel/MaintainScrollPositionOnPostback
if (e.Item.ItemType == ListItemType.EditItem)
e.Item.Cells[i].Attributes["style"] = "width:80px;";
public static void ConfirmRedirect(Page page, string msg, string url)
{
string script = $@"if(confirm('{msg}')) location.href='{url}';";
ScriptManager.RegisterStartupScript(page, page.GetType(), "confirm", script, true);
}
這 25 個技巧覆蓋了 WebForms 開發 80% 的高頻場景。建議收藏備查,並在團隊內建立共享 Snippet 庫(Visual Studio 代碼片段 / GitHub Gist),讓新人快速上手、老手減少重複造輪子。