Celaro
Celaro

Reputation: 226

KnockoutJs: dataObject is not defined

I have a simple WebApi project to manipulate returned data in various format. I am trying to use KnockoutJs to consume the data at the front end but I am having a variable not defined error that I can't seem to understand why. Below is the simple code I am working on. Please feel free to point out the errors. Thanks

Controller formats

[httpGet]
public Object Data
{
  return new {
   Time: DateTime.now,
   Text: "<b>Salut</b>",
   Count: 1
  };
}

JS front end

<script>
    $(document).ready(function(){
    $.ajax("/api/formats", {
       success: function(data){
          dataObject = ko.observable(data);
          ko.applyBindings();
       }
    };
 });

HTML

    <tbody>
       <tr>
         <td>Time</td>
         <td data-bind="text: dataObject().Time">
         <td>Text</td>
         <td data-bind="text: dataObject().Text">
      </tr>
   </tbody>

Upvotes: 1

Views: 217

Answers (1)

Pedram
Pedram

Reputation: 828

At first,your variable dataObject does not have Time and Text properties, so you should check it in your code as following:

var dataObject = ko.observable();
ko.applyBindings();
  
function doBinding() {
    var data = {
        Time: "XYZ",
        Text: "<b>Salut</b>",
        Count: 1
    };
    
    dataObject(data);        
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div>

  <div data-bind="text: dataObject() ? dataObject().Time : 'No Data'"></div>
  <div data-bind="text: dataObject() ? dataObject().Text : 'No Data'"></div>
  
<div>

<button onclick="doBinding()">binding</button>

Upvotes: 1

Related Questions