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
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
Use a Hidden Field
control.
Update the Hidden Field
to 1 on Button Client
Click.
Update the Session Value
in the Page Load' event. The Value will be 1 then update the Session variable and set the
Hidden Fieldvalue to 0 underneath the
Session Variable` Update.
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..
- Preinit
- Init
- InitComplete
- PreLoad
- Load
- Control Event
- Load Complete
- Pre Render
Hope this will help you...