选择元素的初始值 [英] Select element's initial value
本文介绍了选择元素的初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用初始值初始化select
.我有一个从我的后端返回的Json对象,像这样:
I would like to initialize a select
with an initial value. I have a Json object returned from my backend like this one:
[{Nom:"xxx", TypeIld:1, ....},{Nom:"xxx", TypeId:1, ....}]
我有一个像这样声明的typeId数组:
I have an array of typeIds declared like this :
[{ Nom: "Plats", TypeId: 0 },
{ Nom: "Crudités", TypeId: 1 },
{ Nom: "Tartes Salées", TypeId: 2}]
我想将我的所有记录显示在一个表中,并且将选择的typeId初始化为正确的值.
I would like to display all my records in a table with a select for the typeId initialized to the correct value.
这是我的代码:
<form class="PlatsCuisinesEditor">
<table data-bind="visible: platscuisines().length > 0">
<thead><tr><th></th><th>Nom</th><th>Description</th><th>Prix</th><th>Frequence</th><th>Type</th><th></th></tr></thead>
<tbody data-bind='template: { name: "PCRowTemplate", foreach: platscuisines }'></tbody>
</table>
<br />
<div style="margin-top:10px;">
<button data-bind="enable: platscuisines().length > 0" type="submit">Enregistrer les plats</button>
</div>
</form>
<script type="text/html" id="PCRowTemplate">
<tr>
<td><input class="required" data-bind="value: Nom, uniqueName: true"/></td>
<td>
<select data-bind="options: viewModel.platstypes, optionsText:'Nom'"></select>
</td>
</tr>
</script>
<script type="text/javascript">
var initialData = @Html.Raw(Json.Encode(ViewBag.JsonPlats));
var dataFromServer = ko.utils.parseJson(ko.toJSON(initialData));
//var testTypesPlats = @Html.Raw(Json.Encode(ViewBag.platsTypes));
var viewModel = {
platscuisines: ko.observableArray(dataFromServer),
platstypes : [{ Nom: "Plats", TypeId: 0 },{ Nom: "Crudités", TypeId: 1 },{ Nom: "Tartes Salées", TypeId: 2}],
};
ko.applyBindings(viewModel);
</script>
推荐答案
您希望编写如下选择:
<select data-bind="options: viewModel.platstypes,
optionsText:'Nom',
optionsValue: 'TypeId',
value: TypeId">
</select>
这告诉Knockout您想使用platstypes
中的TypeId
属性作为选项的值,并告诉它从
This tells Knockout that you want to use the TypeId
property from platstypes
as the value for your options and tells it to read/write the value of the field from the TypeId
property of each item in platscuisines
这篇关于选择元素的初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文