Prasad
Prasad

Reputation: 59511

Call javascript function from global.asax in asp.net mvc

How to call or make the javascript function from the Application_Start of global.asax in asp.net mvc(C#) application?

Upvotes: 0

Views: 3528

Answers (4)

Ε Г И І И О
Ε Г И І И О

Reputation: 12371

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.

You can skip the registration if the variable is set.

Upvotes: 0

queen3
queen3

Reputation: 15521

You can remember the last "invoked" time in Session or cookies (which is easier for javascript but worse for performance/etc) and then

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().

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.

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. 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;
  3. Run function above but like this: if (!inited) timer = $.getJSON("/timer?uid=x"); and when you have the precise current timer you can continue with JavaScript only, without server requests.

Upvotes: 1

&#199;ağdaş Tekin
&#199;ağdaş Tekin

Reputation: 16651

Since JavaScript executes on client side and global.asax executes on server side. You cannot do that.

Upvotes: 0

LiamB
LiamB

Reputation: 18586

"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"

This wouldnt be the place to do it.

Have you thought about using your masterpage?

Upvotes: 0

Related Questions