原理:使用 RaisePostBackEvent 方法捕获回发,并在服务器上引发 Click 事件。
需求:通过asp:GridView渲染的列表,能够点击某一行数据,获取当行的变量参数,以此触发后端方法。
前端代码:
<asp:GridView ID="gridView" RowStyle-CssClass="login-list" runat="server" Width="100%" CellPadding="3" AutoGenerateColumns="False" ShowHeader="false" BorderWidth="0px" OnRowDataBound="gridView_RowDataBound">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Label runat="server" ID="lbUserId" Text='<%# "用户ID:"+Eval("userid") %>'></asp:Label>
<asp:Label runat="server" ID="lbUserName" Text='<%# Eval("username")+"("+Eval("mobile")+")" %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:Image ID="img" ImageUrl="/assets/weixin/images/arr-right.png" CssClass="right-arr" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
后端代码
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class wap_WxLogin : System.Web.UI.Page, IPostBackEventHandler
{
///......
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = this.Page.ClientScript.GetPostBackEventReference(this, "ClickFlag:" + e.Row.RowIndex.ToString());
Label lbUserName = (Label)e.Row.Cells[0].FindControl("lbUserName");
string username = "" + DataBinder.Eval(e.Row.DataItem, "username");
string mobile = "" + DataBinder.Eval(e.Row.DataItem, "mobile");
mobile = MyFunctions.MobileNubSafety(mobile);
lbUserName.Text = username + "(" + mobile + ")";
}
}
/// <summary>
/// 客户端点击行回传行号,从而定位点击哪一行
/// </summary>
/// <param name="eventArgument"></param>
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
if (eventArgument.StartsWith("ClickFlag:"))
{
int rowIndex = 0;
int.TryParse(eventArgument.Substring(10), out rowIndex);
try
{
GridViewRow row = gridView.Rows[rowIndex];
Label lbUserId = (Label)row.Cells[0].FindControl("lbUserId");
string UserId = "" + lbUserId.Text;
UserId = UserId.Replace("用户ID:", "");
string openId = "" + HttpContext.Current.Session.Contents["openid"];
LoginByOpenId(openId, UserId);
}
catch (Exception ex)
{
MyFunctions.WriteError(ex);
MyFunctions.ShowErrorByLayer("登录失败!");
return;
}
}
}
}