Note: This answer was written in 2011 and looking at it nowadays, it's more of a hack. It's better to load values through AJAX request that hits a JSON endpoint API.
Here's a practical case:
I have a GlobalSettings static C# class that contains static Properties of values that are used through the whole system in the ASP.NET MVC backend side of things.
Some of those values need to be shared with JS code. So I created an Action that returns JavaScriptResult which basically pumps out those values into global JS variables.
Note: Change the output cache period to suit your needs
[OutputCache(Duration = 999999)]
public virtual JavaScriptResult Global()
{
var script = $@"
MaxNotificaitonsToShow = {GlobalSettings.MaxNotificaitonsToShow};
ItemsPerPage = {GlobalSettings.ItemsPerPage};
";
return JavaScript(script);
}
And then I load the response of this action as a JS file inside all pages through the HTML footer:
<script type="text/javascript" src="/JS/Global"></script>
Now I can get the values in any Javascript file:
if(ItemsPerPage == 25)
{
alert('it works!');
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…