简体   繁体   English

在ASP.NET MVC中从global.asax调用javascript函数

[英]Call javascript function from global.asax in asp.net mvc

如何从asp.net mvc(C#)应用程序中的global.asax的Application_Start调用或制作javascript函数?

You can remember the last "invoked" time in Session or cookies (which is easier for javascript but worse for performance/etc) and then 您可以记住会话或cookie中的最后一次“调用”时间(对于JavaScript来说更容易,但对性能/等而言则更糟),然后

function check() {
   // or var lasttime = <%= Session["lasttime"] %>;
   if (now - $.cookie("lasttime") > timeout)
   {
     $.cookie("lasttime", now);
     performAction();
   }
   window.setTimeout(check, 1000);
}

You can call time function once from $(document).ready(). 您可以从$(document).ready()调用一次时间函数。

But note that it may take browser several seconds to render page, or it may bump into 404 or other errors and page will be inactive... javascript is not a reliable way to do scheduled actions. 但是请注意,浏览器可能需要花费几秒钟来呈现页面,或者可能会碰到404或其他错误,并且页面将处于非活动状态... javascript不是执行预定操作的可靠方法。

Another way is to have your timer on server . 另一种方法是将计时器放在服务器上 JavaScript function like above will just ask for it from time to time, passing user ID or something like that. 上面的JavaScript函数会不时要求它,传递用户ID或类似的东西。 This will prevent timer reset during page reload. 这将防止在页面重新加载期间重置计时器。 But you'll have to do request too often. 但是您必须经常请求。 So the best solution would be to combine two techniques: 因此最好的解决方案是结合两种技术:

  1. Run timer on server 在服务器上运行计时器
  2. When page is renders, set var inited = false; 呈现页面时,设置var inited = false;
  3. Run function above but like this: if (!inited) timer = $.getJSON("/timer?uid=x"); 运行上面的函数,但是像这样:if(!inited)timer = $ .getJSON(“ / timer?uid = x”); and when you have the precise current timer you can continue with JavaScript only, without server requests. 而当您拥有精确的当前计时器时,则可以仅使用JavaScript,而无需服务器请求。

"The javascript function gets the data to be shown to the User from database through jquery. The javascript function will be executed periodically using setTimeout" “ javascript函数通过jquery从数据库获取要显示给用户的数据。javascript函数将使用setTimeout定期执行”

This wouldnt be the place to do it. 这不是这样做的地方。

Have you thought about using your masterpage? 您是否考虑过使用母版页?

Since JavaScript executes on client side and global.asax executes on server side. 由于JavaScript在客户端执行,而global.asax在服务器端执行。 You cannot do that. 你不能这样做。

How about you check a Application level variable at the load of your landing page (master page would also do) and register whatever the javascript there and set the variable. 您如何在着陆页加载时检查应用程序级变量(母版页也会这样做)并在那里注册任何javascript并设置变量。

You can skip the registration if the variable is set. 如果设置了变量,则可以跳过注册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM