sanakkian
sanakkian

Reputation: 299

Accessing session information in JavaScript

I am newer one in ASP.net. I want to store text in the text box from JavaScript to session variables and pass those session variables to client side JavaScript. Is this possible?

Upvotes: 1

Views: 456

Answers (1)

GregL
GregL

Reputation: 38121

You will need to do this in the code behind.

To store the value from the textbox in the session, in the correct event handler you would need to put code like:

if (!IsPostback) {
    Session("TextboxContent") = txtTextbox.Text;
}

And to populate it in client side javascript, it depends on if you are using a library or not, but something that should work regardless is to have the following in your markup:

<script type="text/javascript">
    var tb = document.getElementById('<%= txtTextbox.ClientID');
    if (tb) tb.value = '<%= Session("TextboxContent").ToString().Replace("'", @"\'") %>';
</script>

Note that having code like I have done here in <%= %> ("alligator tags") is generally considered pretty bad practice, but you can use an <asp:Literal> or whatever if you like.

Upvotes: 1

Related Questions