In Asp.net MVC 3, the Session and ViewBag values are transferred to Javascript. The main methods include:
1. Use Javascript Variable
Suppose there is 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>
Add to your View:
@ Section my_script_variables {
<Script type = "text/javascript">
Var variable1 = '@ myvar1', variable2 =' @ Session ["myVar2"] ', variable3 =' @ ViewBag. myvar3 ';
</Script>
}
Suppose you have the following Value:
@ {String myVar1 = "First"; Session ["myVar2"] = "Second"; ViewBag. myVar3 = "Third ";}
In the external Js file, you get the alert message of First Second Third.
Alert (variable1 + ''+ variable2 +'' + variable3 );
2. Use the features of Controller
You can add a parameter to your control.
<Input type = "hidden" value = "@ Session [" myVar2 "]" id = "myHiddenVar"/>
Then
Alert ($ ('# myHiddenVar'). val ());
You can also use the Data feature:
<A id = "myLink" data-variable1 = "@ myVar1" data-variable2 = "@ Session [" myVar2 "]" data-variable3 = "@ ViewBag. myVar3">
Test </a>
Then in the JS referenced outside:
$ ('# Mylink'). click (function (){
Alert ($ (this). data ('variable1') + ''+ $ (this). data ('variable2') +'
'+ $ (This). data ('variable3 '));}
);
We get the same result.
3. RazorJS
You can install it from NuGet. It allows you to write Razor-style C # code in the Js file.
View:
@{
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 );
Then in external. Js:
@{
Var myobj = (Dictionary <string, string>) Model;
}
Alert ('@ myobj ["var1"]' + ''+ '@ myobj [" var2 "]' +'' + '@ myobj ["var3"]');
The final result is the same.
Hope to help your Web development.
Author: Petter Liu