This post explains different ways to get Session, ViewBag or server side variable’s values in your external JS files. In Rich UI web app, there are many JS files having thousands lines of code and It’s common to need of accessing server side variable or session in external js file. Let’s see different ways to get it in ASP.NET MVC 3.
razor javascript file2 Pass Session or Viewbag values to JS Files : ASP.NET MVC 3

1. Using Javascript Variable:

In your view page, you can access session or server side objects easily. So, declare javascript variables, assign Session or ViewBag values and use those variables in JS files.
But your javascript variables must be declared before calling external file. For this, Add section in <head> of layout page(say _layout.cshtml).

<head>
	...
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

    @RenderSection("my_script_variables", false)

    <script src="@Url.Content("~/Scripts/external.js")" type="text/javascript"></script>
	...
   
</head>

and in your view page:

@Section my_script_variables {

    <script type="text/javascript">
            var variable1 = '@myVar1',
            variable2 = '@Session["myVar2"]',
            variable3 = '@ViewBag.myVar3';
           
        </script>

}

Suppose you have following values:

@{
    String myVar1 = "First";
    Session["myVar2"] = "Second";
    ViewBag.myVar3 = "Third";
 }

and in external js file:

 alert(variable1 + ' ' +variable2 +' '+ variable3);

then you will get ‘First Second Third‘ alert message.

2. Using Control’s Attributes:

You can assign Parameters as value of control

    <input type="hidden" value="@Session["myVar2"]" id="myHiddenVar" /> 

and get it in js file easily

  alert($('#myHiddenVar').val());

the output in our case is second.

You can use Data Attribute also

 <a id="myLink" data-variable1="@myVar1" data-variable2="@Session["myVar2"]" data-variable3="@ViewBag.myVar3">Test</a>

and in external js file

 $('#myLink').click(function () {            
            alert($(this).data('variable1')+' ' +$(this).data('variable2')+' '+$(this).data('variable3'));
            }); 

On clicking test link, the output is ‘First Second Third‘.

3. RazorJS:

You can add RazorJS by using Nuget. It allows to write Razor-Style C# or VB.NET inside your Javascript Files. Right now, It supports Model and Url Only means you can’t access Session and ViewBag in js (Hope, It’ll be implemented soon).

If the view is NOT strongly typed(means model type is not specified) then you can pass your parameters as model in javascript. Let us see following example:

In view page

@{
   
    String var1 = "First";
    Session["var2"] = "Second";
    ViewBag.var3 = "Third";

    Dictionary<string, string> test1 = new Dictionary<string, string>();
    test1.Add("var1", var1);
    test1.Add("var2", Session["var2"].ToString());
    test1.Add("var3", ViewBag.var3);    
  
}
  @Html.RazorJSInline("~/Scripts/external.js", test1);

Here, you notice all required parameters in js file are added in dictionary and pass as a model.

In external.js

@{
var myobj = (Dictionary<string, string>)Model;
}
alert('@myobj["var1"]' +' '+ '@myobj["var2"]'+' ' +'@myobj["var3"]');

The output is ‘First Second Third‘ alert.

Note: RazorJSInline takes second parameter as Model. If model type is not specified in view then you can pass any data type(as you’ve seen above). If model is specified then you have to pass object of same data type(you can modify values of object).

Hope, It helps. Share your opinion and let us know how you are passing parameters in external js files.

Comments:  5

  • Guest

    yz answer

  • Rohan

    Very Good suggestion Dude.
    It works perfectly  for me

  • http://twitter.com/karrlander Björn Kärrlander

    Thanks for the tips. I try to pass as much as I can as function parameters. If it’s more than two-three parameters (or if I wanna reuse) then I create a DTO-object containing the parameters and pass that into a stand alone function or for example into an init-function of another object or module. It’s slightly more cumbersome but I get a little less spaghetti that way and it’s easier to test.

    /Björn

  • Manuel Mejia Jr.

    thanks you!!!!

  • leavelbw

    Excellent. A very clean and precise answer to a seemingly complex issue. Thanks.