我正在尝试构建一个在 Azure 上托管的免费网站,它使用 MVC4 和 KnockoutMVC。该网站每 4 秒从 Controller 更新一个表。该代码在本地执行没有问题,但是当我将其部署到 Azure 网站时,它不处理更新。
我现在已经开始了一个全新的 MVC 4 项目,其中有一些使用 knockout 的简单功能,显示当前时间,并从 Controller 每 0.5 秒更新一次,它使用与我的 javascript 相同的结构为正确的网站编写。它给出了同样的问题,并且看起来好像 ko.ServerAction 调用正在停止 javascript 函数。
查看
@using PerpetuumSoft.Knockout
@model MVCHelloWorld.Models.HelloWorldModel
@{
var ko = Html.CreateKnockoutContext();
}
<script type="text/javascript">
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
@ko.ServerAction("Index", "HelloWorld");
t = setTimeout(function() { startTime(); }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>
<body onload="startTime()">
<h2>Hello World - 2</h2>
<div id="time"></div>
<label>Knockout time</label>
@ko.Html.Span(m => m.Time)
</body>
@ko.Apply(Model)
Controller
namespace MVCHelloWorld.Controllers
{
public class HelloWorldController : BaseController
{
public HelloWorldModel model = new HelloWorldModel();
public ActionResult Index()
{
GetTimeDoCalculation();
return View();
}
public void GetTimeDoCalculation()
{
model.Time = DateTime.Now.ToString("H:mm:ss");
}
}
}
型号
namespace MVCHelloWorld.Models
{
public class HelloWorldModel
{
public string Time { get; set; }
}
}
最佳答案
尝试将其添加到您的 View 正文中:
<script type="text/javascript">
@* Replace 4000 with the timeout, in milliseconds *@
window.setInterval(startTime, 4000)
</script>
您的整个 View 将如下所示:
@using PerpetuumSoft.Knockout
@model MvcApplication2.Models.HelloWorldModel
@{
var ko = Html.CreateKnockoutContext();
}
<script type="text/javascript">
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
@ko.ServerAction("Index", "HelloWorld");
t = setTimeout(function() { startTime(); }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>
<body onload="startTime()">
<h2>Hello World - 2</h2>
<div id="time">
<script type="text/javascript">
@* Replace 4000 with the timeout, in milliseconds *@
window.setInterval(startTime, 4000)
</script>
<label>Knockout time</label>
@ko.Html.Span(m => m.Time)
</div>
</body>
@ko.Apply(Model)
关于asp.net-mvc - Knockout MVC - ServerAction 调用未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17216191/