Asp.net mvc set session variable in javascript

11,597

No, session variables are server side. You'd have to have a little ajax call to talk to the server to set it. There are plenty of examples of this via google searches. You can see one example here.

For a one-time evaluation (on the server, before it hits the client), you can set it (sort of) in the code section of your script, but I think that's different from what you're asking to do. See this thread.

Share:
11,597
ucnobi ucnobi
Author by

ucnobi ucnobi

Updated on June 04, 2022

Comments

  • ucnobi ucnobi
    ucnobi ucnobi almost 2 years

    I am trying to set session value in javascript :

    //session value 5400
    //remainingSeconds value 5399
    @Session["remain-seconds"] = remainingSeconds;
    

    But i am getting the following error:

    invalid left-hand side in assignment

    Is it possible to set session variable inside javascript?

  • ucnobi ucnobi
    ucnobi ucnobi over 8 years
    I am using setinterval to implement countdown timer. It would be heavy process to send ajax request in every second. I did it because user can change javascript variable from console and i need unchangable global variable in javascript
  • Nikki9696
    Nikki9696 over 8 years
    There's options for that sort of thing. Session isn't one of them. =) Please open a new question for recommendations on ways to solve your underlying problem.
  • ucnobi ucnobi
    ucnobi ucnobi over 8 years
    Okey i found solution, simple wrap inside (function(){ : )))