Call server side Method from JavaScript after Timer count down end in ASP.Net

Last Reply 5 months ago By dharmendr

Posted 5 months ago

Hi Developers,

I am creating a Exam page . so i want to put a timer on my page , i have tried lots using c#,but no one is working exactly. si i am added timer using javascript code . i have to call c# function from javascript when the time countdown is 0.

i have done and working but i dont know how to call C# server side Function from javascript .

my html code

<h3>
 Session Time <span id="countdown">10</span> seconds
</h3>

my javascript code 

<script type="text/javascript">

    // Total seconds to wait
    var seconds = 3;

    function countdown() {
        seconds = seconds - 1;
        if (seconds < 0) {
            // Chnage your redirection link here        
           
            window.location = "test.aspx";
            //UpdateTime(time);
          
        } else {
            // Update remaining seconds
            document.getElementById("countdown").innerHTML = seconds;
            // Count down using javascript
            window.setTimeout("countdown()", 1000);
        }
    }

    // Run countdown function
    countdown();

</script>

my C# code

protected void Page_Load(object sender, EventArgs e)
    {

    }
    public void MyName(object sender, EventArgs e)
    {
        name();
    }
    public void name()
    {
        lbl.Text = "Paul Raj";
    }

i need to bind the C# MyName() function and Display the name "Paul Raj" after the countdown end .am trying , if anyone know this kindly help me to done this module , this is the last module of my project.

 

thanking you

Paul.S

'man becomes what he thinks about'

Posted 5 months ago Modified on 5 months ago

Hi paulrajmca,

Check this example. Now please take its reference and correct your code.

For calling code behind method from client side refer below article.

Call Code Behind function from Client Side (JavaScript) in ASP.Net

HTML

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<h3>
    Session Time <span id="countdown">10</span> seconds
</h3>
<asp:Label ID="lbl" runat="server" />
<script type="text/javascript">
    var seconds = 3;
    function countdown() {
        seconds = seconds - 1;
        if (seconds < 0) {
            PageMethods.name(function (response, userContext, methodName) {
                document.getElementById("<%=lbl.ClientID%>").innerHTML = response;
            });
        } else {
            document.getElementById("countdown").innerHTML = seconds;
            window.setTimeout("countdown()", 1000);
        }
    }
    countdown(); 
</script>

C#

[System.Web.Services.WebMethod]
public static string name()
{
    return "Paul Raj";
}

Screenshot