I am just looking into knockout.js with MVC-Web-API and I am trying to create a Hello World page that will update the time on the page every 5 seconds. It is making the call every 5 seconds, I can see this in my controller (breakpoint), but still nothing displays on screen.
UPDATE: I have still been working on this, and I have now established that I am getting the data back from the server, the call is being made to the controller every 5 seconds, and it is returning the JSON I need (alerts are showing this) however there is still nothing displaying on the span element on the page.
I realistically need to use the mapping function as I am developing a larger website, that has a model with over 50 properties and don't particularly want to go through and map them individually to in the viewmodel.
I have included my code below.
<span data-bind="text: TimeString"></span>
<script type="text/javascript">
var viewModel;
var getUpdates = setInterval(function () {
$.getJSON(
"/Values/Get", {},
function (model) {
alert(model.TimeString);
ko.mapping.fromJS(model, viewModel);
});
}, 5000);
$(document).ready(
function () {
$.getJSON(
"/Values/Get", {},
function (model) {
var viewModel = ko.mapping.fromJS(model);
alert(model.TimeString);
ko.applyBindings(viewModel);
});
});
function bindViewModel(model) {
ko.applyBindings(model);
}
public class HelloWorldModel
{
public DateTime TimeDT { get; set; }
public String TimeString { get; set; }
}
public class ValuesController : Controller
{
public HelloWorldModel Model = new HelloWorldModel();
[System.Web.Mvc.AcceptVerbs(HttpVerbs.Get)]
public JsonResult Get()
{
Model.TimeDT = DateTime.Now;
Model.TimeString = Model.TimeDT.ToString("HH:mm:ss");
return Json(Model, JsonRequestBehavior.AllowGet);
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}