5

I am using MVC3 with Razor View engine,

i have .cshtml page in that i have a JavaScript function, inside that JavaScript function, i want to create Session variable and retrieve that session in same JavaScript function.

how to achieve this..

3
  • 1
    Did you try to do so? and i think sessions are server variables. Commented Apr 16, 2013 at 12:51
  • 1
    I think you are asking the same questions here. Besides why would you want to create a session item in js? Remember that js runs on the client. So do you intend to do another http call and set a session item? Commented Apr 16, 2013 at 12:54
  • @vonv. My previous code to creating a Session variable in JavaScript was wrong thats why i asked separated question for that.. Commented Apr 16, 2013 at 13:24

2 Answers 2

14

Description

The Session is on the server side so you need to call the server in order to set or retrieve session variables.

Just post to a controller and set the Session variable there.

Sample

jQuery

$(function () {
    $.post('/SetSession/SetVariable', 
           { key : "TestKey", value : 'Test' }, function (data) 
    {
        alert("Success " + data.success);
    });
});

Mvc Controller

public class SetSessionController : Controller
{
    public ActionResult SetVariable(string key, string value)
    {
        Session[key] = value;

        return this.Json(new { success = true });
    }
}

More Information

Sign up to request clarification or add additional context in comments.

Comments

-1

To add a session with the javascript code. just must be to add this code

sessionStorage.setItem("MyId", 123);

and you can use this code to call the added session

var value = sessionStorage.getItem("MyId");

2 Comments

Please add some explanation to your answer such that others can learn from it
thanks for getting my attention, I hope the description you added helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.