javascript - 将 Razor 变量传递给 JavaScript 函数

标签 javascript c# jquery asp.net-mvc

我正在 Asp.net MVC 中的一个拍卖网站上工作,我正在尝试能够显示每件元素的拍卖还剩多少时间的计时器。我使用我的模型将项目列表传递到我的 cshtml 页面,然后像这样遍历它们:

我的启动计时器的 javascript 函数:

function countdown(time) {
    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance = time - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Display the result in the element with id="timeLeft"
    document.getElementById("timeLeft").innerHTML = days + "d " + hours + "h "
        + minutes + "m " + seconds + "s ";

}, 1000);

然后是我模型的迭代器,用项目的结束日期调用 js 函数

@foreach (var item in Model)
    {
        //code here
        countdown(@item.EndDate)
        <text id="timeLeft"></text>
    }

我的脚本被 <script src="~/Scripts/countdown.js" /> 引用了

The problem I am having is how to call this js function with a c# razor variable. Doing something basic for one item like:

<body onload= "countdown('@item.EndDate')">

When I put my razor variable it greys out my function. How do I need to go about passing my variable into my js function?
EX: (with singular Model item)
enter image description here enter image description here

最佳答案

试试这个语法:

@foreach (var item in Model)
{
    //code here
    countdown(`${@item.EndDate}`)
}

关于javascript - 将 Razor 变量传递给 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51198880/

相关文章:

javascript - setState 是否可以使用编号键将新条目添加到对象的开头?

javascript - 从左侧和右侧计算溢出的列表项。 (不是顶部/底部)

javascript - 如何在单页中添加多个不可见的验证码?

c# - 在 WPF 中解析本地 XML 文档(调试工作,发布后失败)

javascript - 无法使用 FileReader 操作元素

javascript - Firefox 无法正确显示图像 (CSS + HTML)

javascript - 如何让 oninput() 只在输入汉字而不是 IME 击键时触发?

javascript - windows.scroll通过在顶部添加固定滚动值

C# RegEx 模式将字符串拆分为 2 个字符的子字符串

c# - 使用 SQL SERVER 2008 处理 XML 和 XML 验证?