Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting session value in aspx page

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

like image 217
SharpCoder Avatar asked Sep 20 '26 04:09

SharpCoder


2 Answers

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...! :)

like image 176
SHEKHAR SHETE Avatar answered Sep 23 '26 11:09

SHEKHAR SHETE


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.

like image 30
IgnasK Avatar answered Sep 23 '26 10:09

IgnasK



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!