Reputation: 1783
I'm using Knockout for the first time, It looks extremely easy but I'm not able to do some simple things which can be done.
My HTML File
<tbody data-bind="foreach: LOBModel">
<tr>
<td data-bind="text:lob_ID"></td>
<td data-bind="text: lob_Name"></td>
<td data-bind="text: lob_Description"></td>
</tr>
</tbody>
My JS File
$(window).load(function () {
getLOB();
//var vm = {
// LOBModel: [
// { lob_ID: 'Bert', lob_Name: 'Bertington', lob_Description: 'Bertington' },
// { lob_ID: 'Charles', lob_Name: 'Charlesforth', lob_Description: 'Bertington'},
// { lob_ID: 'Denise', lob_Name: 'Dentiste', lob_Description: 'Bertington' }
// ]
//}
//ko.applyBindings(vm);
//Commented Section Work
function getLOB() {
$.ajax({
url: '/Admin/GetLOB',
type: "POST",
dataType: "json",
success: function (returndata) {
alert(returndata.data);
var LOBModel = ko.mapping.fromJS(returndata);
ko.applyBindings();
},
error: function () {
}
});
}
});
In my Controller I'm passing the data as follows
public JsonResult GetLob()
{
SLADAL objDal = new SLADAL();
return Json(objDal.GetLOB());
}
Please help.
I'm getting
0x800a139e - Microsoft JScript runtime error: Unable to parse bindings.
Message: TypeError: 'LOBModel' is undefined;
Bindings value: foreach: LOBModel
EDIT: For those who are looking for a complete Ajax Get and Post Example using JSON Array of object, this is a useful link i've found. hope this helps some body.
URL : http://www.dotnetcurry.com/showarticle.aspx?ID=847
Keep Coding :D
Upvotes: 0
Views: 1173
Reputation: 1271
To bind your data to the viewmodel you'll first have to pass it as an argument to the binding method (I'm guessing the LOBModel is an array), like this:
var LOBModel = ko.mapping.fromJS(returndata);
ko.applyBindings(LOBModel);
Then when you access it later on in the html you'll have to use the $root
keyword.
<tbody data-bind="foreach: $root">
<tr>
<td data-bind="text:lob_ID"></td>
<td data-bind="text: lob_Name"></td>
<td data-bind="text: lob_Description"></td>
</tr>
</tbody>
For more great examples you could always take the interactive tutorial at http://learn.knockoutjs.com/
If you want to add more functionality to your viewmodel you could always create it like this:
var LOBModel = ko.mapping.fromJS({
data: returndata,
yourFunctionHere: function () {
...
}
});
ko.applyBindings(LOBModel);
Then you'll have to modify your HTML to look like, I've also added the click event as an example of how to access the viewmodel from within a knockout context:
<tbody data-bind="foreach: $root.data">
<tr>
<td data-bind="text: lob_ID, click: $root.yourFunctionHere"></td>
<td data-bind="text: lob_Name"></td>
<td data-bind="text: lob_Description"></td>
</tr>
</tbody>
Upvotes: 1