DIV CSS 佈局教程網

在 GridView 中讀取當前點擊行的 DropDownList 與 TextBox 值
編輯:JavaScript綜合知識     

ASP.NET Web Forms 的 GridView 裡,一行往往包含下拉框、文本框等控件。當用戶點擊該行的操作鏈接時,需要把同一行其他控件的值一併取走。用 jQuery 配合 DOM 層級關係可以很簡潔地做到。

ASPX 頁面

<asp:GridView ID="GridView1" runat="server">
<Columns>
  <asp:BoundField HeaderText="ID" DataField="ID" />
  <asp:BoundField HeaderText="Name" DataField="ID" />
  <asp:BoundField HeaderText="Url" DataField="ID" />

  <asp:TemplateField>
    <ItemTemplate>
      <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Value="0">保密</asp:ListItem>
        <asp:ListItem Value="1">男</asp:ListItem>
        <asp:ListItem Value="2">女</asp:ListItem>
      </asp:DropDownList>
    </ItemTemplate>
  </asp:TemplateField>

  <asp:TemplateField>
    <ItemTemplate>
      <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
    </ItemTemplate>
  </asp:TemplateField>

  <asp:TemplateField>
    <ItemTemplate>
      <a href="#" onclick="Save(this); return false;">Save</a>
    </ItemTemplate>
  </asp:TemplateField>
</Columns>
</asp:GridView>

jQuery 腳本

<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function Save(obj) {
  var tr = $(obj).parent().parent(); // 由 a 標簽向上找到所在行

  // 第四列 DropDownList1 的選中值與顯示文本
  var ddlValue = tr.find("td").eq(3).find("select").val();
  var ddlText  = tr.find("td").eq(3).find("select").find("option:selected").text();

  // 第五列 TextBox 的值
  var txtValue = tr.find("td").eq(4).find("input").val();

  console.log(ddlValue, ddlText, txtValue);
}
</script>

原理說明

核心思路是「先定位行,再在行內查找」。點擊事件傳入 this(即 a 標簽本身),一層 parent() 到 td,再一層到 tr,於是拿到了整行的上下文。之後所有 find 都被限制在這一行的範圍內,不會誤取其他行的數據。

取下拉框值用 val(),取顯示文本則需要 option:selected 的 text()——原示例中寫的 find("select").text() 會返回所有選項拼接起來的文本,並非當前選中項,這裡已作修正。列索引從 0 開始,所以第四列是 eq(3),第五列是 eq(4)。

幾點改進建議

用硬編碼的列序號取值很脆弱:一旦調整列順序或增刪列,所有索引都要跟着改,也容易出錯。更穩妥的做法有兩種。

其一,給控件指定 ClientIDMode="Predictable" 並用 ClientID 定位,或直接給 a 標簽傳入行索引,通過 $("#GridView1 tr").eq(rowIndex) 定位。

其二,把需要的值提前寫進 data-* 屬性,例如 <a data-id="..." onclick="Save(this)">,用 $(obj).data('id') 直接讀取,完全不必依賴列的位置。

另外,示例中的 a 標簽點擊後 href="#" 會讓頁面積累歷史記錄,建議補上 return false(示例已加)或改用 button 元素。若要收集整行數據提交,也可以考慮直接用 __doPostBack 走服務端事件,讓 GridView 的 RowCommand 通過 GridViewRow 對象訪問控件,省去前端拼裝。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved