Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How to Set values to Session in Javascript

Tags:

javascript

c#

I want to set the Dropdown selected value in Session. I have done in Code behind. But for some condition i have to Do in Client Side Itself. i tried the following. but i did't solution yet.

<%Session["Test"] = "Welcome Mamu";%>  
var session_value='<%=Session["Test"]%>';  
alert(session_value);

The above work fine. Note that i have assign Static value(Welcome Mamu). but for Dynamatic,

var strTest=document.getElementById('DropDownList1').value;  
<%Session["Test"] = "'+ strTest +'";%>

It is Working fine in Client Side. But i Server Side(Code Behind), the Session["Test"] value is '+ strTest +'.

Is any other way to assign values to Session?

like image 595
pratik patel Avatar asked May 01 '26 02:05

pratik patel


2 Answers

You can not do what you want and mix those 2. :-)

The first is a server code and the second is a client code.

The server code runs PRIOR to the client code

What can you do ?

create hidden input element :

<input  type='hidden' id='h' name='h'/>

var h=document.getElementById('h') ;
h.value=document.getElementById('DropDownList1').value;

And when you post the page :

you get the value by :

Session["Test"]=Request.Form["h"]+"";
like image 177
Royi Namir Avatar answered May 02 '26 15:05

Royi Namir


Well, what you're asking for doesn't really make sense. The session is stored on the server. Your JavaScript can't interact with it directly.

Server code blocks run when ASP.Net renders the page:

<% Some code %>

So this will work:

<% Session["Test"] = "Welcome Mamu"; %>

Because you're setting the value to a fixed string... It's the same as writing Session["Test"] = "Welcome Mamu"; in your code behind.

What you need to do, is save your value in a hidden field or similar and retrieve that and update the session in your code behind.

<asp:hiddenfield id="ValueHiddenField" runat="Server" />

var strTest=document.getElementById('DropDownList1').value;
document.getElementById('<% ValueHiddenField.ClientId %>').value = strTest;

Then you can update the value in your code behind like:

Session["Test"] = ValueHiddenField.Value;
like image 28
RobH Avatar answered May 02 '26 15:05

RobH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!