0

I have a problem of setting value on HiddenFiled with javascrip on ASP.NET my HiddenFiled code is:

<asp:HiddenField ID="hidden" Value="before" runat="server" />

my JS code in ASP.NET is:

function HandleIT(id) {

    alert(document.getElementById('<%=hidden.ClientID %>').value);

    document.getElementById('<%=hidden.ClientID %>').value = "test";

    alert(document.getElementById('<%=hidden.ClientID %>').value);

    <%Session["search"] = hidden.Value;%>

    window.location.assign("Search.aspx");
}

so the first alert show me "before" and the second one show me "test". so far so good. but when it goes to Search.aspx and i am using Session["search"] its showing me "before" any idea why is it happaning?

Humayun Shabbir
  • 2,961
  • 4
  • 20
  • 33
SIE-Coder
  • 105
  • 1
  • 7

2 Answers2

0

This line:

<%Session["search"] = hidden.Value;%>

get the value from codebehind that is rendered before any changes by client-side. So the value is the default value of field when is was rendered at first.

EDIT:
I think you can't set the session exactly in this way and in the ASPX page. It's because lifecycle of ASP.net. You have to do a postback to get the new value of hidden field. Postback maybe call to a full postback or partial postback or even an ajax postback.

I think that maybe it's possible using a public propery at first, but it is not. You can check This

As you know even when we want to pass value from javascript to codebehind, we have to use hiddenfields like This.

Anyway i think you have to set the session's value in codebehind.

Community
  • 1
  • 1
Moshtaf
  • 4,833
  • 2
  • 24
  • 34
0

The code that sets the session variable gets run when the page is rendered and before the JavaScript is run. This is the difference between client n server side code.

matt_lethargic
  • 2,706
  • 1
  • 18
  • 33
  • There are many tricks to do that, but your code is not complete and it's hard to provide a perfect help. When the `HandleIT` is called? you can assign an codebehind click event to a button or hidden button in codebehind set the session. – Moshtaf Aug 05 '14 at 11:11