在SAPUI5中从json将文档显示到文本框中

时间:2016-01-26 10:48:44

标签: javascript json sapui5

我想使用SAPUI5将数据显示在JSON的文本框中。

// JSON sample data
var data = {
    firstName: "John",
    lastName: "Doe",
    birthday: {day:01,month:05,year:1982},
    address:[{city:"Heidelberg"}],
    enabled: true
};

// create JSON model instance
var oModel = new sap.ui.model.json.JSONModel();
// set the data for the model
oModel.setData(data);
// set the model to the core
sap.ui.getCore().setModel(oModel);

// create your controls        
var oTextView = new sap.ui.commons.TextView("textView", {
    // bind text property of textview to firstName property in the model
    text: "{/firstName}",
    tooltip: "First Name"
});
var oTxt = new sap.ui.commons.TextField("txtField", {
    // bind text property of textfield to firstName property in the model
    value: "{/firstName}"
});

上面的代码正在运行,但是当我在JSON文件中传输json数据并尝试加载此方案数据时,我没有加载。

现在我的Json文件看起来像:

{
  "UserDetails":[
{
  "userid": "Test-Id", 
  "sapname": "Test-SAP-Form", 
  "age": 37, 
  "annualleave": 32
}
]}

在Json文件中传输Json数据时,我使用下面的代码加载数据:

var userDetailsModel = new sap.ui.model.json.JSONModel();
userDetailsModel.loadData("json/UserDetails.json");
userDetailsModel.setData("json/UserDetails.json");
sap.ui.getCore().setModel(userDetailsModel, "UserDetails");

但我无法将数据显示到TextBox中。

我的错误是什么?

1 个答案:

答案 0 :(得分:1)

数据绑定的(简单)语法是{model>path},因此当您执行setModel(model, "modelname")时,您需要执行{modelname>path}

在您的情况下,所需的值是

var oTxt = new sap.ui.commons.TextField("txtField", {
    // bind text property of textfield to firstName property in the model
    value: "{UserDetails>/firstName}"
});

并删除model.setData行,如他的评论中提到的Qualiture

编辑:您的JSON文件与传递给控件的路径不同。使用该结构,您需要将路径设置为{UserDetails>/UserDetails/0/firstName}