Web Server Timer Functionality

It is a tiny and useful ASP.NET MVC web application to obtain web server timer functionality. We can say, we can get response along with any data from server after some time interval. Let’s see how:

Now, let's create a simple ASP.NET MVC web application in VS 2015. We will get server date and time in this application.

Open Visual Studio 2015 and go to menu File à New à Project.

Select path and name of the project, select ASP.NET MVC web application template, and save the project.

Add script to index.cshtml page.

Code for calling the AJAX request to server method “GetServerTime()” from our jQuery code.

  1. <script type="text/javascript">  
  2.     // Update the count down every 1 second    
  3.     var x = setInterval(function() {  
  4.         //alert('Get user data');    
  5.         var serverTime;  
  6.         $.ajax({  
  7.             type: "POST",  
  8.             url: "@Url.Action("  
  9.             GetServerTime ")",  
  10.             data: {},  
  11.             contentType: "application/json; charset=utf-8",  
  12.             dataType: "json",  
  13.             success: function(data) {  
  14.                 $("#time").html(data.time);  
  15.             },  
  16.             failure: function(errMsg) {  
  17.                 alert(errMsg);  
  18.             }  
  19.         });  
  20.     }, (1000));  
  21. </script> 

In HomeController.cs class, we implement “GetServerTime()” method that returns JSON result.

  1. public JsonResult GetServerTime() {  
  2.     return Json(new {  
  3.         time = Convert.ToString(DateTime.Now)  
  4.     });  
  5. }  

In success code block of AJAX request function, as mentioned in the above JavaScript code, we insert time in the inner HTML of div by getting with id “time”.

  1. success: function (data) { $("#time").html(data.time); },  

That’s it. Using this technique, we can get or post any type of data to server or into database.

Ebook Download
View all
Learn
View all