使用 ViewData 跟踪每页加载的脚本
我目前正在尝试找到一种仅在需要时加载 JavaScript 文件的好方法。为了做到这一点,我为faceboxlinks、datepickerfields、tinymcefields 和其他需要外部js 和初始化jquery 表达式的脚本创建了几个HtmlHelpers。 在这些帮助程序中,我使用 jQuery 的 getScript() 执行脚本,并使用其回调函数来初始化脚本。
现在我的问题来了。我最初的想法是在字符串列表中跟踪这些脚本并将其放入 htmlHelper.ViewData 中。但是,不幸的是,这失败了。由于某种原因,此视图数据不会传递给部分视图或类似的东西;它不保留列表..
是否有另一个地方可以全局保存我的字符串列表而不是助手的 ViewDataDictionary,或者我是否以错误的方式使用此 ViewData?我应该出于某种原因传递它吗? 任何澄清或帮助将不胜感激!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 HttpContext.Current.Items 集合来存储与当前请求相关的数据。
不过,我认为您应该重新设计您的架构,以便它不依赖于全局变量(ViewData 和 Items 最终在您的情况下)。
看看这个:如何添加JavaScript 到 ASP.NET MVC 视图? 和类似的。
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: How do I add JavaScript to an ASP.NET MVC View? and similar.