将远程方法添加到 GridView 事件

Add remote method to GridView event

我有一个 aspx 网络应用程序,它有多个 GridView,方法相似。我的想法是创建一个具有可重用方法的 "helper" class。我的问题是利用这些远程 class 方法的最佳方式是什么?

前端不接受这样的 class.method:

<asp:GridView runat="server" ID="myGridView" ... OnSorting="myClass.reusableMethod"
当我在 Page_Load 上附加处理程序时,

Visual Studio 没有给我任何编译错误,但我确实收到一个运行时错误,说 GridView 试图触发事件但它没有那里。

if (!IsPostBack)
{
    myGridView.Sorting += myClass.reusableMethod;
}

我很确定最后的方法会奏效,但似乎适得其反。像往常一样在页面后端创建方法,但只有一行是对远程方法的调用

public void myGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    myClass.reusableMethod();
}

可以做到。首先从 GridView 中删除 OnSorting 事件。

<asp:GridView ID="myGridView" runat="server" AllowSorting="true">

然后只绑定IsPostBack检查之外的方法。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //do not bind the event here
    }

    //but here
    myGridView.Sorting += myClass.reusableMethod;
}

现在您可以使用方法

public static void reusableMethod(object sender, GridViewSortEventArgs e)
{
    GridView gv = sender as GridView;
}