views:

50

answers:

1

Hi all,

I'm currently trying to find a good way to load my javascript files only when I need them. In order to do this, I created several HtmlHelpers for faceboxlinks, datepickerfields, tinymcefields and other scripts that need an external js and an initialisation jquery expression. In these helpers I execute the script using jQuery's getScript() and use its callback function to init the script.

Now my problem comes. My initial thought was to keep track of these scripts in a List of Strings and put this in htmlHelper.ViewData. But, unfortunately this fails. For some reason, this viewdata isn't passed to partial views or something similar; it doesn't keep the list..

Is there another place where I can globally keep my list of strings instead of the ViewDataDictionary of the helper, or am I using this ViewData in a wrong way and should I pass it on for some reason? Any clarification or help would be very appreciated!

A: 

You can use HttpContext.Current.Items collection to store data that is relevant to the current request.

Though, I think you should redesign your architecture, so that it does not rely on global variables (which ViewData and Items end up being in your case).

Have a look at this: http://stackoverflow.com/questions/694111/how-do-i-add-javascript-to-an-asp-net-mvc-view and similar.

HeavyWave
Thanks! The use of HttpContext.Current.Items did the trick. For now, this solves my problem. What exactly could be the disadvantages of relying on global variables in this sort of situations?I'm not very keen on the idea of having to define and initialize my scripts in every view I use..
Leon
When you use global variable you skip the architectural constraints altogether, so it's theoretically harder to support such code. You don't have to initialize all your scripts at once, you can do it on demand like you do now, but add the initialization code to the relevant placeholder in the container, which is then added to the master page. This way your master page doesn't have to "know" anything about the views.
HeavyWave
I see, thanks for clearing that up :)
Leon