首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET WebForms 開發常見 25 個實用技巧總結(含代碼片段)

     編輯:ASP.NET 基礎

前言

ASP.NET WebForms 雖屬經典模式,但在大量存量專案中仍佔主流。本文彙總 25 個高頻實用技巧,涵蓋彈窗傳參、確認對話框、GridView 交互、日期/數字格式化、全局變量、異常處理、腳本技巧等,附可直接複製的代碼片段,作為開發手邊速查手冊。

技巧清單

1. 新窗口打開並傳參

// 服務端打開新窗口
Response.Write("<script>window.open('Detail.aspx?id=" + ddl.SelectedValue + "')</script>");
// 接收端
string id = Request.QueryString["id"];

2. 按鈕確認對話框

// 簡單版
btnDelete.Attributes["onclick"] = "return confirm('確定刪除?');";
// 完整邏輯版
btnDelete.Attributes["onclick"] = "if(confirm('確定?')){return true;}else{return false;}";

3-4. GridView 刪除記錄與確認提示

// 獲取 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('確定刪除此行?');";

5. 行點擊/雙擊跳轉

// 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 ❌

6. HyperLinkColumn 傳參新窗口

<asp:HyperLinkColumn Target="_blank" 
    DataTextField="Title" 
    DataNavigateUrlFields="Id" 
    DataNavigateUrlFormatString="Detail.aspx?id={0}" />

7. 行點擊/懸停變色

// 點擊變色
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='';";

8. 日期格式化

// GridView BoundField
DataFormatString="{0:yyyy-MM-dd}" HtmlEncode="false"
// 代碼中
lbl.Text = dt.Rows[0]["CreateTime"].ToString("yyyy-MM-dd");

9. 錯誤頁面友好跳轉(保留異常詳情)

// 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 會丟失。

10. 清除 Cookie

Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);

11. 自定義異常 + 事件日誌記錄

public class AppException : ApplicationException
{
    public AppException(string msg) { EventLog.WriteEntry("MyApp", msg, EventLogEntryType.Error); }
}

// 使用
throw new AppException("庫存不足");

12. Panel 橫向滾動、縱向自適應

<asp:Panel Style="overflow-x:auto; overflow-y:auto; max-height:400px;">...</asp:Panel>

13. Enter 鍵當 Tab 用

<script>
document.onkeydown = function(e) {
    if (e.keyCode === 13 && !['button','submit','reset','textarea'].includes(e.target.type))
        e.keyCode = 9;
};
</script>

14. DataGrid 超鏈接列跳轉

DataNavigateUrlFields="Id" DataNavigateUrlFormatString="Edit.aspx?id={0}"

15. DataGrid 行鼠標懸停變色(伺服端綁定)

e.Item.Attributes["onmouseover"] = "this.style.background='#EFF3F7';";
e.Item.Attributes["onmouseout"] = "this.style.background='" + e.Item.Style["BACKGROUND-COLOR"] + "';"

16. TemplateColumn 模板列:顯示/編輯/全選 CheckBox

<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;

17. 數字格式化(貨幣、千分位)

<%# Eval("Price", "{0:¥#,##0.00}") %>
// 代碼中
price.ToString("N2"); // 1,234.56

18. 日期驗證正則(支援多種分隔符、閏年)

// 簡化版:yyyy-MM-dd 或 yyyy/MM/dd
^\d{4}[-/](0[1-9]|1[0-2])[-/](0[1-9]|[12]\d|3[01])$

19. 全局變量

// Global.asax
Application["AppStartTime"] = DateTime.Now;
// 讀取
var start = (DateTime)Application["AppStartTime"];

20. ASP.NET Menu 點擊新窗口

<MenuItem ... UrlTarget="_blank" />

21. 讀取 GridView 編輯行 TextBox 值

foreach (GridViewRow row in gv.Rows)
{
    var txt = (TextBox)row.FindControl("txtQty");
    // ...
}

22. 模板列客戶端自動計算:數量 × 單價 = 金額

<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>

23. SmartNavigation 防止回發頁面跳頂

// Page_Load
Page.SmartNavigation = true; // 僅 IE 支援,現代瀏覽器請用 UpdatePanel/MaintainScrollPositionOnPostback

24. 編輯模式 TextBox 寬度控制

if (e.Item.ItemType == ListItemType.EditItem)
    e.Item.Cells[i].Attributes["style"] = "width:80px;";

25. 服務端彈窗確認並跳轉

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),讓新人快速上手、老手減少重複造輪子。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved