简体   繁体   English

无法将Rest JSON数据绑定到WinJS中的ListView控件

[英]Could not able to bind Rest JSON data to ListView control in WinJS

I am facing a problem. 我正面临一个问题。 I am trying to bind a ListView WinJS control to a RESTful service that return a JSON object. 我试图将ListView WinJS控件绑定到返回JSON对象的RESTful服务。

Here is my design (default.html) 这是我的设计(default.html)

<body>
    <button id="btnExample">REST Service</button>

    <div id="divDisplayItems" data-win-control="WinJS.Binding.Template">
        <div>

            <table border="1">
                <tr>
                    <td><b>PersonId</b></td>
                    <td><b>PersonName</b></td>                 
                </tr>
                <tr>
                    <td><h4 data-win-bind="innerText: PersonId"></h4></td>  
                    <td><h4 data-win-bind="innerText: PersonName"></h4></td> 
                </tr>
            </table>            
        </div>
    </div> 
    <div 
        id="basicListView" 
        style="width:250px;height:500px"
        data-win-control="WinJS.UI.ListView" 
        data-win-options="{itemDataSource :SourceData.itemList.dataSource, itemTemplate: select('#divDisplayItems'),layout : {type: WinJS.UI.ListLayout}}"
        >
    </div>
</body>

Here is my default.js code 这是我的default.js代码

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());            
            document.getElementById("btnExample").addEventListener("click", JSonRecord, false);
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    function JSonRecord(event) {

        WinJS
            .xhr(
                    { url: "URL/EmployeeList" }
                 )
            .then
                 (
                    function (response) {

                        var sourceData = JSON.parse(response.responseText);

                        var datalist = new WinJS.Binding.List(sourceData.EmployeeDetailsResult);

                        var dataMembers = { itemList: datalist };

                        WinJS.Namespace.define("SourceData", dataMembers);                       

                    }, function (error)
                    {
                        console.log(error);
                    }
                 );
    } 
    app.start();
})();

Intension is that whenever the "btnExample" is cliekd, the ListView should be populated. 内容是每当“btnExample”被cliekd时,应该填充ListView。 The service is working fine and I am able to get proper data. 该服务工作正常,我能够获得适当的数据。 But the moment I am trying to load the page, it is crashing. 但是在我尝试加载页面的那一刻,它正在崩溃。

If I comment 如果我评论

"data-win-options="{itemDataSource :SourceData.itemList.dataSource, itemTemplate: select('#divDisplayItems'),layout : {type: WinJS.UI.ListLayout}}"

the at least the page is loading. 至少页面正在加载。

What is the problem and how can I bind the data to the ListView Control ? 有什么问题,如何将数据绑定到ListView控件?

Thanks 谢谢

You are binding the ListView to the SourceData namespace which is not available until AFTER you click the button. 您将ListView绑定到SourceData命名空间,该命名空间直到您单击按钮后才可用。 Thus, you are trying to bind to a undefined value at runtime. 因此,您尝试在运行时绑定到未定义的值。 You should set up the SourceData namespace at the top of your js file, prior to the activated event, and create it with an empty Binding List . 您应该在激活的事件之前在js文件的顶部设置SourceData命名空间,并使用空的绑定列表创建它。 Something like... 就像是...

WinJS.Namespace.define("SourceData", {
   itemList: new WinJS.Binding.List([]);
})

In your button click handle, you can just add the items to the existing list or create a new one and assign it from scratch. 在按钮单击手柄中,您只需将项目添加到现有列表或创建新项目并从头开始分配。

There are some great tutorials that you can find at 30 Days , especially in Week 2 IIRC. 您可以在30天内找到一些很棒的教程,尤其是第2周的IIRC。

You're crashing because when you load the page and the ListView tries to bind, your list doesn't exist. 您正在崩溃,因为当您加载页面并且ListView尝试绑定时,您的列表不存在。 It doesn't exist until after your asynchronous call to your web service. 在您异步调用Web服务之后,它才会存在。 All you need to do to fix it is declare your WinJS.Binding.List earlier (perhaps just above your app.onactivated line next to the app alias). 你需要做的就是修复它早于声明你的WinJS.Binding.List(可能就在app别名旁边的app.onactivated行上方)。 Then when you fetch your data, just iterate the results and push them into the already-existing List. 然后,当您获取数据时,只需迭代结果并将它们推送到已存在的List中。 Like this... 像这样...

sourceData.EmployeeDetailsResult.forEach(function(r) {
    yourList.push(r);
}

2 changes in Default.js Default.js中的2个更改

First Change 第一次改变

var app = WinJS.Application; var app = WinJS.Application;

/* insert the line / *插入行

WinJS.Namespace.define("SourceData", 
    {
        itemList: new WinJS.Binding.List([])
    })

*/ * /

var activation = Windows.ApplicationModel.Activation; var activation = Windows.ApplicationModel.Activation;

Second Change 第二次改变

function (response) 
{

  var sourceData = JSON.parse(response.responseText);                      
  var datalist = new WinJS.Binding.List(sourceData.EmployeeDetailsResult);

 <-- basicListView is the Name of the div where you are binding the datasource -->
  basicListView.winControl.itemDataSource = datalist.dataSource;                      

}

Watch this video for a better understanding. 观看视频以获得更好的理解。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM