【问题标题】:ASP.Net: Adding client side onClick to a HyperlinkField in GridViewASP.Net:将客户端 onClick 添加到 GridView 中的 HyperlinkField
【发布时间】:2010-05-30 10:31:53
【问题描述】:

我有一个现有的 GridView,其中包含“合作伙伴名称”字段。它可以按合作伙伴名称排序。
现在我需要更改合作伙伴名称字段,并在某些情况下使其可点击和 alert() 一些东西。

现有代码为:

  <asp:GridView ID="gridViewAdjustments" runat="server" AutoGenerateColumns="false" AllowSorting="True" OnSorting="gridView_Sorting" OnRowDataBound="OnRowDataBoundAdjustments" EnableViewState="true">
         <asp:BoundField DataField="PartnerName" HeaderText="Name" SortExpression="PartnerName"/>

我已添加列:

<asp:hyperlinkfield  datatextfield="PartnerName" SortExpression="PartnerName" headertext="Name" ItemStyle-CssClass="text2"/>

这使我能够控制 CSS 和排序。但是,我找不到如何向其添加客户端 javascript 函数。
我发现添加:

    <asp:TemplateField HeaderText="Edit">                                     
<ItemTemplate>
      <a id="lnk" runat="server">Edit</a>      

使我能够通过 id 访问“lnk”并添加到它的属性。但是,我失去了排序能力。

在这种情况下,正确的解决方案是什么?
谢谢。

【问题讨论】:

    标签: asp.net gridview c#-3.0


    【解决方案1】:

    我找到的解决方案是以这种方式使用 asp:TemplateField,而不会失去排序能力并使用 Eval 使用 datatextfield:

     <asp:TemplateField HeaderText="Name" SortExpression="PartnerName">
    <ItemTemplate>
            <a onclick="javascript:alert('ok')" href="http://<%#Eval("PartnerName")%>"><%#Eval("PartnerName")%></a>
    </ItemTemplate></asp:TemplateField>
    

    【讨论】:

      【解决方案2】:

      处理RowDataBound 事件。在事件处理程序中...

      private void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         e.Row.Cells[0].Controls[0].Attributes.Add("onclick", "alert(‘An alert’);")
      }
      

      您可能需要将Controls[0] 更改为Controls[1]

      【讨论】:

      • 定义ID时的错误是:“Id属性对于不是从Control继承的标签无效”。
      • 谢谢 - 但你仍然不能给 asp:hyperlinkfield 一个 ID...不过我明白你的意思。
      • 是的,我忘了删除那个位。
      【解决方案3】:

      生成的 ClientId 看起来与 ID 完全不同,但它总是以 ID 结尾。我们不能在 Javascript 或 Jquery 中使用 ID,所以我们可以这样做:

       <asp:TemplateField  SortExpression="partnername" HeaderText="Partner">
          <ItemTemplate>
            <asp:HyperLink ID="kkx" Text='<%#Eval("partnername")%>'  NavigateUrl="# runat="server">
            </asp:HyperLink>
          </ItemTemplate>
          </asp:TemplateField>
      

      然后在 Jquery 中我们可以这样做:

      $(function() {
               $("#GridView1 a[id$=kkx]").bind('click', function() {
                   alert('hi');
                });
            });
      

      【讨论】:

        【解决方案4】:

        jQuery.简单的单行和unobtrusive

        $('A.text2').click(function() {
            alert('ok');
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-29
          • 1970-01-01
          • 1970-01-01
          • 2020-03-09
          • 1970-01-01
          • 2011-03-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多