I want to assign some value to a session variable via JavaScript in my aspx page.
var name = e.object.text;
<%# Session["CurrentName"] = name %>
Above code is giving following error:
Compiler Error Message: CS0103: The name 'name' does not exist in the current context
When I googled all the post are about getting the value from session in JavaScript. But I want to set the value to a session variable in JavaScript code.
How can I assign value to session variable in JavaScript?
Thank you
Accessing & Assigning the Session Variable using Javascript:
See Here
Assigning the ASP.NET Session Variable using Javascript:
<script type="text/javascript">
function SetUserName()
{
var userName = "Shekhar Shete";
'<%Session["UserName"] = "' + userName + '"; %>';
alert('<%=Session["UserName"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetUserName()
{
var username = '<%= Session["UserName"] %>';
alert(username );
}
</script>
Hope this helped you...! :)
You can't, at least not like this.
JavaScript is client-side thus rendered after the server-side (C#). That means you can't assign session values directly through JavaScript.
One way to solve your problem would be to use AJAX to asyncronously send a request to server and change value of the session.
Example how to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With