首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP.NET 首頁 RadioButton 值傳遞至下一頁作為搜尋條件

     編輯:程式設計綜合問答

核心原理

RadioButton 本質是 <input type="radio">,**放在 <form> 內**,表單提交時瀏覽器會自動將「被選中的 radio 的 name/value」送至伺服器,與文字框無異。

實作步驟

1. 首頁 Default.aspx

<form id="form1" runat="server" method="post" action="SearchResults.aspx">
    <div>
        <asp:RadioButton ID="rdoType1" GroupName="searchType" Text="類型 A" Value="A" runat="server" />
        <asp:RadioButton ID="rdoType2" GroupName="searchType" Text="類型 B" Value="B" runat="server" />
        <asp:RadioButton ID="rdoType3" GroupName="searchType" Text="類型 C" Value="C" runat="server" />
    </div>
    <asp:TextBox ID="txtKeyword" runat="server" />
    <asp:Button ID="btnSearch" Text="搜尋" runat="server" />
</form>
  • GroupName 確保單選互斥。
  • Value 屬性為提交時的實際值(ASP.NET RadioButton 預設不輸出 value,需手動加或用 InputAttributes["value"] = "A")。
  • action="SearchResults.aspx" 直接導向處理頁。

2. 處理頁 SearchResults.aspx.cs

protected void Page_Load(object sender, EventArgs e) {
    if (IsPostBack) return; // 避免重複處理

    // 方式一:Request.Form 取原始表單值(最通用)
    string selectedType = Request.Form["searchType"]; // name=searchType 的被選 radio 值
    string keyword = Request.Form["txtKeyword"];

    // 方式二:若用 Server.Transfer,可用 PreviousPage.FindControl
    // string selectedType = ((RadioButton)PreviousPage.FindControl("rdoType1")).Checked ? "A" : ...;

    // 執行查詢
    if (!string.IsNullOrEmpty(selectedType)) {
        BindGrid(selectedType, keyword);
    }
}

關鍵細節

  1. name 一致:同組 RadioButton 的 name (即 GroupName) 必須相同,瀏覽器才只送一個值。
  2. value 設定:ASP.NET RadioButton 預設不渲染 value,需在 Page_Load 或 PreRender 手動加:
    rdoType1.InputAttributes["value"] = "A";
  3. 跨頁回傳:若用 PostBackUrl 或 Server.Transfer,配合 PreviousPage 取控制項值更型別安全。

完整可運作範例

<!-- Default.aspx -->
<form runat="server" action="Result.aspx" method="post">
  <input type="radio" name="cate" value="news" checked /> 新聞
  <input type="radio" name="cate" value="blog" /> 部落格
  <input type="radio" name="cate" value="video" /> 影片
  <input type="text" name="q" placeholder="關鍵字" />
  <button type="submit">搜尋</button>
</form>

<!-- Result.aspx.cs -->
string cate = Request.Form["cate"]; // "news" | "blog" | "video"
string q = Request.Form["q"];

原生 HTML 寫法最輕量、最好懂,ASP.NET WebForms 控制項只需補 value 即可。

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