Question

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

Was it helpful?

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

OTHER TIPS

  1. Use a Hidden Field control.

  2. Update the Hidden Field to 1 on Button Client Click.

  3. Update the Session Value in the Page Load' event. The Value will be 1 then update the Session variable and set theHidden Fieldvalue to 0 underneath theSession Variable` Update.

  4. Reason for the Usage of Page Load event is that on clicking the Button as per the page life cycle the page events like PreInit, Init, InitComplete, PreLoad, Load executes before the execution of Button Control.

Page events execution takes place like below..

  1. Preinit
  2. Init
  3. InitComplete
  4. PreLoad
  5. Load
  6. Control Event
  7. Load Complete
  8. Pre Render

Hope this will help you...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top