Error with the Knockout framework's inability to bind to the model

I seem to be encountering an issue with binding Knockout to a model in my code. Despite the code firing and returning a JSON object, the table appears empty. Any advice or suggestions would be greatly appreciated.

HTML

  <table style="border: double">
   <thead>
    <tr>
     <td>jobId</td>
    </tr>
   </thead>
   <!--Using foreach to iterate through an observableArray-->
   <tbody data-bind="foreach: Jobs">
    <tr style="border: solid" data-bind="click: $root.getselectedjob" id="updtr">
    <td><span data-bind="text: $data.jobId "></span></td>
    </tr>
   </tbody>
  </table>

Javascript

var JobViewModel = function () {
    var self = this;
    self.jobId = ko.observable("");
    self.name = ko.observable("");
    self.description = ko.observable("");

    var jobData = {
        jobId: self.jobId,
        name: self.name,
        description: self.description
    };

    self.Jobs = ko.observableArray([]);

    GetJobs(); 

    function GetJobs() {
        $.ajax({
            type: "GET",
            url: "/Client/GetJobs",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                debugger;
                self.Jobs(data); 
            },
            error: function (error) {
                alert(error.status + "<--and--> " + error.statusText);
            }
        });
    }

    self.getselectedjob = function (job) {
        self.jobId(job.jobId),
        self.name(job.name),
        self.description(job.description)
        
    };


};
ko.applyBindings(new JobViewModel());

C# Method for retrieving jobs

    public ActionResult GetJobs(string AccountIDstr)
    {
        int AccountID = Convert.ToInt32(AccountIDstr);
        AccountID = 1;

        var jobs = (from c in db.jobs
                          select c).OrderByDescending(m => m.jobId).ToList();

        var jobsFilter = (from e in jobs
                                 where (AccountID == null || e.accountId == AccountID)
                                 select e).ToList();


        var jobsresult = from jobrows in jobsFilter
                      select new
                      {
                          jobId = jobrows.jobId.ToString(),
                          name = jobrows.name,
                          description = jobrows.description
                      };

        return Json(new
        {
            Jobs = jobsresult
        },
                    JsonRequestBehavior.AllowGet);
    }

JSON Object

{"Jobs":[{"jobId":"5","name":"Job 5 ","description":"Job 5 description"},{"jobId":"1","name":"Job 1 ","description":"Job 1 description"}]}

Answer №1

Ensure that your Jobs is an observableArray, with the data wrapped in an object. When setting the value in GetJobs, use the following code:

self.Jobs(data.Jobs);

Below is a functioning snippet that can be executed with your ajax function to populate data. If it does not work, check the response you are receiving.

var JobViewModel = function() {
  var self = this;
  
  self.jobId = ko.observable("");
  self.name = ko.observable("");
  self.description = ko.observable("");

  var jobData = {
    jobId: self.jobId,
    name: self.name,
    description: self.description
  };

  self.Jobs = ko.observableArray([]);

  GetJobs();

  function GetJobs() {
    var data = {
      "Jobs": [{
        "jobId": "5",
        "name": "Job 5 ",
        "description": "Job 5 description"
      }, {
        "jobId": "1",
        "name": "Job 1 ",
        "description": "Job 1 description"
      }]
    };
    setTimeout(function() {
      self.Jobs(data.Jobs);
    }, 500);

  }

  self.getselectedjob = function(job) {
    self.jobId(job.jobId),
      self.name(job.name),
      self.description(job.description)
  };
};

ko.applyBindings(new JobViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js"></script>
<table style="border: double">
  <thead>
    <tr>
      <td>jobId</td>
    </tr>
  </thead>
  <tbody data-bind="foreach: Jobs">
    <tr style="border: solid" data-bind="click: $root.getselectedjob" id="updtr">
      <td><span data-bind="text: $data.jobId "></span>
      </td>
    </tr>
  </tbody>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the functionalities of RestSharp API in conjunction with GustPay

Currently, I am engaging with the RestSharp Api to interact with the GustPay Api. However, I find myself perplexed about how to properly include the "api_key" and "api_secret" in the request. var client = new RestClient("https://www.gustpay.com/api/gust_p ...

Steps to refresh a variable when the SMS read plugin successfully completes

I'm attempting to make a post call within the success callback of my SMS read plugin code. I can successfully print _this.otpnumber in the console. Please refer to my stack trace image link getSMS(){ var _this= this; var fil ...

Is your Angular2 form page experiencing reloading issues?

I am currently incorporating Angular2 into my project. I am facing an issue where the page keeps refreshing, and I'm unable to determine the cause. Below is a snippet of my form: <form> <div class="form-group"> ...

HTML and CSS for an off-canvas menu

Looking to create an off-canvas menu that smoothly pushes content out of view instead of cropping it. Additionally, I want to implement a feature that allows the menu to close when clicking outside of it. I found the code for the off-canvas menu on W3Scho ...

What is the best way to enter a varied number of items using Item IDs (strings), with an empty item ID indicating the final item?

When inputting variables as Item ID, I need the program to recognize a blank item as the last input, regardless of how many items are entered. ...

Steps for accessing the "this" keyword within the parent function

Struggling with referencing `this` within a parent function while building a basic tab system using AngularJS. It seems like I may not have a solid grasp on the fundamentals, so any guidance would be appreciated: JavaScript: $scope.tabs = { _this: th ...

What is the method for retrieving a property from an object contained within an array that is assigned to a property of another object?

How can I retrieve the name property from the subjects array within a course object? The database in use is mongodb. Modifying the course model is not an option. The course model : const mongoose = require('mongoose'); const Schema = mongoose. ...

When working with a barcode font in Chrome, using style.fontFamily may not be effective, but utilizing className can achieve the desired result

Take a look at this HTML snippet: <style> .barcode { font-family: 'BC C39 3 to 1 Medium'; } </style> <div><span id='spn'>1234567</span></div> This code will apply a barcode font style: <script> ...

Transitioning from Backbone to AngularJS - What challenges can be expected?

Currently I am deep into a large Backbone project (around 8000 lines of JavaScript, not counting external libraries) and I am contemplating making the switch to AngularJS. At the moment, a significant portion of my code deals with DOM manipulation, event ...

Typedi's constructor injection does not produce any defined output

I am utilizing typedi in a Node (express) project and I have encountered an issue related to injection within my service class. It seems that property injection works fine, but constructor injection does not. Here is an example where property injection wo ...

Sending fragmented files straight to Amazon's s3

Currently seeking straightforward examples of uploading directly to Amazon s3 in chunks without any server-side processing, except for signing the request. I have explored various options, but all examples I have found either focus solely on chunking from ...

What is the correct method for passing body parameters in Alamofire using Swift?

I am working with an API that requires a BODY parameter structured like this: {"answers":[{"qid":2588,"value":["Free Society"]},{"qid":150,"value":["Closing of fSociety"]}],"uniqid":"t4815694"} To handle this, I have created a Data Model called SubmitAns ...

React - Defining a global variable within a React component

Can you explain the process to me? I am trying to set up a variable within a react component class so that I can utilize it in multiple sections of my application. Here is what I have attempted: class ColorPick extends React.Component { colorInput; ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Which one should you choose: JSON or GSON?

My Java application is receiving JSON data from a third-party RESTful web service in the following format: { "widgets":[ [ { "id":25128, "status":"always", "uuid":"96f62edd-fa8a-4267- ...

Updating a database with a loop of React Material UI toggle switches

I am trying to implement a material UI switch feature that can update the Active and De-Active status of users in the database directly from the Admin Panel. Currently, the database updates are functioning correctly when toggling the switches. However, th ...

The return value of a jQuery post request is consistently false

When I click on a tag, my code returns true but the data variable is false. Can you explain why this is happening? $('#AddProvince').click(function () { var url = '@Url.Action("SetProvinceList")'; var id = $('#Province&apo ...

Stop the form from submitting when the Enter key is pressed

I am experiencing an issue with my form that contains around 10 input text boxes. When I press the enter key from an input text box, it skips the text boxes in between and goes directly to the submit button. This problem occurs only when using the keyboard ...

develop the following application and execute the npm run dev command, but encounter the error message: "Command failed with exit code 1."

After executing npx create-next-app@latest followed by npm run dev, I encountered the error message Command failed with exit code 1.. Additionally, when trying to access https://localhost:3000, an error stating ERR_CONNECTION_REFUSED was displayed. Further ...

Vue.js: The chart's dataset has been refreshed

I am utilizing vue-chart.js to create a basic chart. import { Line } from 'vue-chartjs'; export default { extends: Line, mounted() { this.renderChart({ labels: [this.getChartLabels], datasets: [ { label: &a ...