Autorefresh function ASP.NET C#

763 views Asked by At

I have a function in Code behind that returns a Label lblvisible.text

 protected void AutoloadDen()
 {
    //somecode
    lblvisible.Text = //somecode;
    // i want to autorefresh function AutoloadDen in 5s
    //Such as: Autorefresh(AutoloadDen,5s)
 }
2

There are 2 answers

2
Kamran Ajmal On

add a timer control on your asp.net markup and add its Tick event in code behind. set interval time of Timer control to 5000 and in code behind call the AutoloadDean() function in tick event of Timer

0
Guruprasad J Rao On

Use System.Windows.Forms.Timer

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 5000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    AutoloadDen();
}

To call it using ajax you need to write a js function as below:

$(document).ready(function(){
      setTimeout(function(){
          $.ajax({
              url: "yourpage.aspx/AutoloadDen",
              method: "GET",
              dataType: "json",
              success:function(data){
                    $('#yourtextboxid').val(data);
              },
              error:function(data){
                    //Display error message 
              }
          });
      });
});

A little modification in server side method

protected void AutoloadDen()
{
    //somecode
    JavaScriptSerializer serializer = new JavaScriptSerializer()
    return serializer.Serialize(YourText);     
}

No need of using timer on serverside in this case