Search code examples
c#asp.netsessionsession-variablesaspbutton

Setting a session variable before AutoPostBack fires in an asp:Button


How would I go about setting a session variable from the click of an ASP:Button before an AutoPostBack event fires.

Here is what I have right now, but I'm not exactly sure I'm doing this right:

 <asp:Button ID="CommitBTN" runat="server" PostBackUrl="~/MMR_Home.aspx" 
 onclick="CommitBTN_Click" UseSubmitBehavior="true" 
 OnClientClick='<% string temp1 = "true"; Session["ClickedFlag"] = temp1; %>' Text="Commit Changes to Database" />

Would this be the correct way of performing this action or am I going at it completely wrong?

EDIT:

Changed my button tag to this:

 <asp:Button ID="CommitBTN" runat="server" PostBackUrl="~/MMR_Home.aspx" 
 onclick="CommitBTN_Click" OnClientClick="document.getElementById('<%= Hidden.ClientID
  %>').value='1'" UseSubmitBehavior="true" Text="Commit Changes to Database" />

I receive this as my error:

Microsoft JScript runtime error: Unable to set value of the property 'value': object is null or undefined


Solution

  • Use this:

    Inside aspx file:

    <form runat="server">
        <asp:Button ID="CommitBTN" runat="server" Text="Button" onclick="CommitBTN_Click" OnClientClick="document.getElementById('HiddenField').value='Ram'"/>
        <asp:HiddenField ID="HiddenField" runat="server" />
    </form>
    

    Or

    <script type="text/javascript">
        function setMyHiddenField(myValue) {
            document.getElementById('HiddenField').value = myValue;
    }
    </script>
    
    <form runat="server">
    <asp:Button ID="CommitBTN" runat="server" Text="Button" onclick="CommitBTN_Click" OnClientClick="setMyHiddenField('Ram')"/>
    <asp:HiddenField ID="HiddenField" runat="server" />
    

    ==================================================================

    Inside aspx.cs file

    protected void CommitBTN_Click(object sender, EventArgs e)
        {
            Session["ClickedFlag"] = HiddenField.Value;
            Response.Write(Session["ClickedFlag"]);
        }
    

    It is easy to replase "Ram" with your value. ;)

    you can change Ram to temp1 easy:

    setMyHiddenField('temp1')

    Or you can call this function on your another control events befor CommitBTN pressed