【问题标题】:Issue with Knockout not binding to model淘汰赛未绑定到模型的问题
【发布时间】:2015-11-16 22:11:05
【问题描述】:

我在将 Knockout 绑定到模型时遇到问题,这是我的代码。代码触发并返回一个 JSON 对象,但表为空。任何建议将不胜感激。

HTML

  <table  style="border: double">
   <thead>
    <tr>
     <td>jobId</td>
    </tr>
   </thead>
   <!--Iterate through an observableArray using foreach-->
   <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 () {
    //Make the self as 'this' reference
    var self = this;
    //Declare observable which will be bind with UI 
    self.jobId = ko.observable("");
    self.name = ko.observable("");
    self.description = ko.observable("");

    //The Object which stored data entered in the observables
    var jobData = {
        jobId: self.jobId,
        name: self.name,
        description: self.description
    };

    //Declare an ObservableArray for Storing the JSON Response
    self.Jobs = ko.observableArray([]);

    GetJobs(); //Call the Function which gets all records using ajax call

    //Function to Read All Employees
    function GetJobs() {
        //Ajax Call Get All Job Records
        $.ajax({
            type: "GET",
            url: "/Client/GetJobs",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                debugger;
                self.Jobs(data); //Put the response in ObservableArray
            },
            error: function (error) {
                alert(error.status + "<--and--> " + error.statusText);
            }
        });
        //Ends Here
    }

    //Function to Display record to be updated. This will be

    //executed when record is selected from the table
    self.getselectedjob = function (job) {
        self.jobId(job.jobId),
        self.name(job.name),
        self.description(job.description)
        //,
        //self.DeptName(employee.DeptName),
        //self.Designation(employee.Designation)
    };


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

获取工作的C#方法

    public ActionResult GetJobs(string AccountIDstr)
    {
        //parse this as parameter
        int AccountID = Convert.ToInt32(AccountIDstr);
        AccountID = 1;

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

        //"Business logic" method that filter jobs by the account id
        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 对象

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

【问题讨论】:

  • 尝试如下修改 Javascript GetJobs() 但没有成功。

标签: javascript c# json knockout.js


【解决方案1】:

您的Jobs 是一个 observableArray,但数据被包装在一个对象中。当您在GetJobs 中设置值时,您应该这样做

self.Jobs(data.Jobs);

这是一个可运行的 sn-p。您应该能够使用您的 ajax 函数来运行它来填充数据。如果它不起作用,请检查您返回的内容。

var JobViewModel = function() {
  //Make the self as 'this' reference
  var self = this;
  //Declare observable which will be bind with UI 
  self.jobId = ko.observable("");
  self.name = ko.observable("");
  self.description = ko.observable("");

  //The Object which stored data entered in the observables
  var jobData = {
    jobId: self.jobId,
    name: self.name,
    description: self.description
  };

  //Declare an ObservableArray for Storing the JSON Response
  self.Jobs = ko.observableArray([]);

  GetJobs(); //Call the Function which gets all records using ajax call

  //Function to Read All Employees
  function GetJobs() {
    //Ajax Call Get All Job Records
    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);

  }

  //Function to Display record to be updated. This will be

  //executed when record is selected from the table
  self.getselectedjob = function(job) {
    self.jobId(job.jobId),
      self.name(job.name),
      self.description(job.description)
      //,
      //self.DeptName(employee.DeptName),
      //self.Designation(employee.Designation)
  };


};
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>
  <!--Iterate through an observableArray using foreach-->
  <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 代码,但仍然没有运气
  • Roy 您的示例有效,但我无法解决我的问题。我的解决方案虽然返回完全相同的 Json 对象,但表并未呈现结果。
  • 我已经完全用你的javascript替换了javascript,但它仍然没有呈现对象。
  • 您是否使用 jQuery 和 Knockout 的 CDN 库?还是本地的?
猜你喜欢
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-06
  • 2016-11-06
  • 1970-01-01
相关资源
最近更新 更多