单击图像按钮时设置会话变量?

时间:2011-12-26 01:12:23

标签: c# session-variables imagebutton autopostback

页面上有两个图像按钮。单击其中任何一个时,需要在回发页面之前设置会话变量yesID和NoId。我尝试将代码放在每个按钮的单击事件中,但页面在单击事件中运行该代码之前再次加载。如何在单击任一图像时设置2个会话变量?

  <div id="MainPics">
        <div id="RightPic">
            <p>
                <asp:Label ID="FirstPicMemberNameLabel" runat="server" Text="" Font-Bold="True" ForeColor="White"></asp:Label>
            </p>
            <asp:ImageButton ID="FirstPicLink" Width="90%" runat="server" 
                onclick="FirstPicLink_Click" />
        </div>
        <div id="LeftPic">
            <p>
                <asp:Label ID="SecondPicMemberNameLabel" runat="server" Text="" ForeColor="White" Font-Bold="True"></asp:Label>
            </p>
            <asp:ImageButton ID="SecondPicLink" Width="90%" runat="server" 
                onclick="SecondPicLink_Click" />
        </div>
        <div id="skip">
            <asp:LinkButton ID="LBNoChoice" PostBackUrl="~/default.aspx" ForeColor="White" runat="server">Skip - I Can't Choose</asp:LinkButton>
        </div>
    </div>

页面背后的代码

   protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            Session["yesID"] = 0;
            Session["noId"] = 0;
        }
        else
        {
            //Send Session Variables to Database for Storage.

        }    
 }

  protected void FirstPicLink_Click(object sender, ImageClickEventArgs e)
    {
        Session["yesID"] = 1;
        Session["noId"] = 2;
    }

    protected void SecondPicLink_Click(object sender, ImageClickEventArgs e)
    {
        Session["yesID"] =2;
        Session["noId"] = 1;
    }

2 个答案:

答案 0 :(得分:1)

这个逻辑有帮助吗?

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["yesID"] = 0;
        Session["noId"] = 0;
    }
    //else
    //{
        //Send Session Variables to Database for Storage.
    //}
}

protected void FirstPicLink_Click(object sender, ImageClickEventArgs e)
{
    Session["yesID"] = 1;
    Session["noId"] = 2;

    SendSessionVariables(Session["yesID"], Session["noId"]);
}

private void SendSessionVariables(object p, object p_2)
{
    // Your database code here
}

protected void SecondPicLink_Click(object sender, ImageClickEventArgs e)
{
    Session["yesID"] = 2;
    Session["noId"] = 1;

    SendSessionVariables(Session["yesID"], Session["noId"]);
}

答案 1 :(得分:0)

当您单击asp.net图像按钮时,它通常会触发click事件并在未禁用autopostback时调用该方法。如果您确实想要在命中自动回行之前更改会话值,请在onclientclick事件上调用客户端javascript函数,然后从中调用更新会话变量值的服务器页面进行ajax调用。从ajax调用(成功事件)获得响应后,返回true,以便网页继续进行表单回发事件。