I have been playing around with building an ASP.Net MVC4 Application with knockoutjs. I have a text box and a submit button; when the button is pressed whatever is in the textbox is sent to a database via json. I would like to use knockoutjs to immediately update whatever is in the database to the browser, but I have been unable to accomplish this.
Currently the app writes data from the browser to the db correctly and I am able to display it by adding a button that calls the All() function.
JS:
function todo(id, isComplete, task) {
var self = this;
self.Id = id;
self.IsComplete = isComplete;
self.Task = task,
self.Attach = function () {
$.ajax({
url: "/api/Todos/",
type: 'post',
data: ko.toJSON(this),
contentType: 'application/json',
success: function (result) {
}
});
}
}
function todoVM() {
var self = this;
self.todos = ko.observableArray([]);
self.All = function () {
self.todos.removeAll();
$.getJSON("/api/Todos/", function (data) {
$.each(data, function (key, val) {
self.todos.push(new todo(val.Id, val.IsComplete, val.Task));
});
});
};
return self;
}
$(document).ready(function () {
ko.applyBindings(new todoVM(), document.getElementById('display'));
ko.applyBindings(new todo(), document.getElementById('add'));
});
Partial View 1:
<div data-bind="foreach: todos">
<input type="checkbox" data-bind="checked: IsComplete" />
<input class="todoItemInput" type="text" data-bind="value: Task, disable: IsComplete, blurOnEnter: true" />
</div>
<!--<input type="button" id="btnGet" value="Get Todos" data-bind="click: All" />-->
Partial View 2;
<input type="text" data-bind="value: Task" />
<input type="button" value="Add" data-bind="click: Attach" />
$.ajaxcall.