Access and Set Sessions, Tempdata, ViewBag, ViewData values in Javascript

Sometime we need to access variable in JavaScript code whose value we set in code behind file or In case of MVC, in controller. Below sample demonstrate how we can achieve this,
(I know this is very simple and someone may find silly to post, but it's for me because I don't want to surf web again for this.)
Access session in JavaScript :-
            var VariableValue = '@Session["VariableValue "]';
 
Access TempData in JavaScript :-
            var VariableValue = '@TempData["VariableValue"]';
 
Access session In JavaScript :-
            var VariableValue = '@ViewBag.Variable';
 
And to set value in JavaScript, if you are trying to set directly it not possible, I have searched a lot for this this but to no success. 
But there is always some workaround you can do to achieve this. Below list show few of them,
  1. Call the code behind function and assign the session values to session variable.
  2. Store it in a hidden filed, submit it to the server.
  3. Set Session value in JavaScript using JQuery Ajax call
     
Sample demonstrate to set value to session variable using Ajax call.
 
Your script code in view will be,

<script type='text/javascript'>
    function SetSessionVariableValue(value) {
        $.post('../Common/SetSessionVariableValue',
        { key: "Session", value: value }, function (data) {
            //Perform some action you want to do here
            window.location.pathname = '@Url.Action("Home", "Home")';
        });
    }
</script>


Action code will look like,

        [AllowAnonymous]
        public ActionResult SetSessionVariableValue(string key, string value)
        {
            //Set User Session
            Session[key] = value;
            return this.Json(new { success = true });
        }


This is what I am doing currently if anyone has better way to do same, they are welcome to share…J


Comments