7
我想用初始值初始化select
。我從後臺返回這樣一個JSON對象:選擇元素的初始值
[{Nom:"xxx", TypeIld:1, ....},{Nom:"xxx", TypeId:1, ....}]
我已經typeIds數組聲明如下:
[{ Nom: "Plats", TypeId: 0 },
{ Nom: "Crudités", TypeId: 1 },
{ Nom: "Tartes Salées", TypeId: 2}]
我想在表一中顯示我的所有記錄選擇初始化爲正確值的typeId。
這裏是我的代碼:
<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>