如何取消Page.ClientScript.GetPostBackClientHyperlink引起的页面刷新?

时间:2016-10-11 08:22:21

标签: c# asp.net

r.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink((Control)this.gridView, "Select$" + r.RowIndex);

嗨,我使用上面的代码来捕获Asp.net中GridView中一行上的click事件。这段代码可以工作,我能够捕获OnSelectdIndexChanged中新选择的行,但是回发也是导致整页刷新。

有没有办法取消页面刷新但仍然更改所选行而不添加'选择'按钮?

2 个答案:

答案 0 :(得分:2)

您需要GridView中的RowCreated事件才能执行此操作。请参阅以下示例:

protected void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) {
        e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
        e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
        e.Row.ToolTip = "Click to select row";
        e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
    }
}

有关选择没有选择按钮的行的更多信息,您可以看到此链接 - How to implement full row selecting in GridView without select button?

为了防止PostBack,我建议使用之前评论过的UpdatePanel然后删除。以下是将GridView放在UpdatePanel中的示例:

<asp:ScriptManager ID=" ScriptManager1" runat="server"/>
   <asp:UpdatePanel ID=" UpdatePanel1" runat="server">
      <ContentTemplate>
           <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
           </asp:GridView>
      </ContentTemplate>
   </asp:UpdatePanel>

这是一些代码。所以我在评论部分分享了一个链接。请检查。

答案 1 :(得分:1)

您可以使用OnRowDataBound事件向GridView添加属性。

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //add the current row number
            e.Row.Attributes.Add("rowNumber", e.Row.RowIndex.ToString());

            //add an item from the database
            e.Row.Attributes.Add("itemID", DataBinder.Eval(e.Row.DataItem, "database_id").ToString());

            //or add a click directy and redirect with javascript
            e.Row.Attributes.Add("onclick", "location.href='/newPage.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "database_id").ToString() + "'");
        }
    }

如果您未在我的代码段中使用第3个属性,则需要处理行单击客户端。你可以用jQuery做到这一点。

    <script type="text/javascript">
        $(document).ready(function () {
            $("#<%= GridView1.ClientID %> tr").click(function () {
                var rowNumber = $(this).attr("rowNumber");
                var itemID = $(this).attr("itemID");
                alert("This is row number: " + rowNumber + ". It has ID: " + itemID);
            })
        });
    </script>