javascript - 使用 javascript 在 html 页面上显示来自 C# 的计时器

标签 javascript c# html .net

你好,我正在尝试用 c Sharp 实现一个计时器,用于计算秒数并将其显示在我的 html 页面上。但是当我将变量传递给 javascript 时,它始终为 0。我到处搜索答案。

这是我到目前为止的代码:

计时器对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;

/// <summary>
/// Summary description for Class1
/// </summary>
public class TimerEu
{

    private Timer t;
    private int time;

    public TimerEu()
    {
        this.t = new Timer(1000);
        this.time = 0;

        t.Elapsed += new ElapsedEventHandler(RunEvent);
        t.Interval = 1000;
        t.Enabled = true;
    }

    public void RunEvent(object source, ElapsedEventArgs e)
    {
        this.time++;
        Console.WriteLine(time);
    }
    public int getTime()
    {
        return this.time;
    }
}

aspx.cs页面:

public partial class _Default : System.Web.UI.Page
{
    public String[] var=new String[10];
    public TimerEu time;
    public int  testint;

    protected void Page_Load(object sender, EventArgs e)
    {
        time = new TimerEu();
        testint = 0;

        Console.Write("hello"+time.getTime());
        for (int i = 0; i < 10; i++)
            var[i] =Operations.test.convertString();
    }

    public void plus()
    {
        this.testint++;   
    }
}

和 html/javascript 部分:

<form id="form1" runat="server">
    <div>
        <br></br>
        <br></br>
        <br></br>
        <p id="demo" runat="server"></p>

        <script>
            var now=0;

            var x= setInterval(function () {
            //now++;

            now = <%=time.getTime()%>
        //    now =<%=testint%>
         //   <%plus();%>

            document.getElementById("demo").innerHTML = now;
    },1000)
</script>

问题是 javascript 似乎并没有每秒调用 getTime 函数,而是只获取 0 作为输出。我做错了什么?

最佳答案

你必须了解重要的事情。本声明<%=time.getTime()%>在渲染的 html 页面发送到浏览器之前,仅在服务器端执行一次。执行时会被替换为0 (方法调用的结果)。

浏览器只能看到now = 0在这种情况下,JavaScript 代码没有任何意义

关于javascript - 使用 javascript 在 html 页面上显示来自 C# 的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45209306/

相关文章:

C#:通用继承工厂

c# - 使用 Nunit、AutoFixture、NSubstitute 和 AutoSubstituteDataAttribute 定义测试数据的属性

javascript - Bootstrap v4.3 Navbar 没有正确动画折叠的非导航栏元素的显示过渡

javascript - Excel 文件通过 POST 下载 C#(避免 404.15 查询字符串错误)

javascript - jQuery,如果 "a"标签是否有类

javascript - 链接 connect/mapStateToProps/mapDispatchToProps 函数以在 react-redux 中重用代码

python - Django/Wagtail/taggit - 获取模型特定的标签列表

javascript - 使用媒体流时 Web Audio API : FFT data in firefox differ from those in chrome,?

c# - 在 wpf 文本框中开始一个新行

html - 在嵌套的 flexbox 容器中收缩包含图像的 flexbox