Reputation: 1981
I'm developing a SharePoint 2010 Web Part. I would use knockout framework for data-binding.
I have one ascx with this code:
<table>
<tr>
<td>
<label id="lblLastMaintenanceDate">Data ultima manuntenzione:</label>
</td>
<td>
<span id="lastMaintenanceDate" data-bind="text: lastMaintenanceDate"></span>
</td>
</tr>
<tr>
<td>
<label id="lblMaintenanceDescription">Descrizione manuntenzione:</label>
</td>
<td>
<span id="MaintenanceDescription" data-bind="text: maintenanceDescription"></span>
</td>
</tr>
<tr>
<td>
<label id="lblConcept">Concept:</label>
</td>
<td>
<span id="Concept" data-bind="text: concept"></span>
</td>
</tr>
</table>
Inside document.ready() I wrote this code:
$(document).ready(function () {
ko.applyBindings(ShopViewModel);
});
This is my ViewModel:
var ShopViewModel = {
lastMaintenanceDate : ko.observable(),
maintenanceDescription : ko.observable(),
concept : ko.observable(),
GetShopDetail : function (val1) {
$.ajax({
type: "GET",
url: "../_layouts/MyProject/MasterPage.aspx/GetDetails?par1=" + val1,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
cache: false,
async: false,
success: function (result) {
var oJson = eval("(" + result['d'] + ")");
if (oJson.Success) {
var result = oJson.Data;
if (result) {
this.lastMaintenanceDate = String(result.LastMaintenanceDate);
this.maintenanceDescription = String(result.MaintenanceDescription);
this.concept = String(result.SyConceptId);
}
}
else {
WriteToConsole(oJson.Error);
customAlert(oJson.Error, "Error");
}
}
})
}
}
And I call GetShopDetail function with this code:
ShopViewModel.GetShopDetail(val1);
My problem is that data-binding doesn't work.
Can you help me?
Thanks
Upvotes: 0
Views: 81
Reputation: 1073968
Two reasons:
Because this
within your ajax callback is not your viewmodel. If you want it to be, use bind
Because you're replacing your observables with raw properties. Instead, set the value of the observable
So:
success: function (result) {
var oJson = eval("(" + result['d'] + ")");
if (oJson.Success) {
var result = oJson.Data;
if (result) {
// ************** Change on next three lines
this.lastMaintenanceDate(String(result.LastMaintenanceDate));
this.maintenanceDescription(String(result.MaintenanceDescription));
this.concept(String(result.SyConceptId));
}
}
else {
WriteToConsole(oJson.Error);
customAlert(oJson.Error, "Error");
}
}.bind(this) // <===== Change here
Re #2, I suggest working through the Knockout tutorials, as this is one of the most fundamental aspects of KO.
Side note: Don't use eval
to parse JSON. Use JSON.parse
to parse JSON. Or $.parseJSON
.
Upvotes: 1