gpt4 book ai didi

选择元素的初始值

转载 作者:行者123 更新时间:2023-12-02 06:43:55 25 4
gpt4 key购买 nike

我想用初始值初始化select。我有一个从后端返回的 Json 对象,如下所示:

[{Nom:"xxx", TypeIld:1, ....},{Nom:"xxx", TypeId:1, ....}]

我有一个像这样声明的 typeId 数组:

[{ 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>

最佳答案

您希望将您的选择写成:

<select data-bind="options: viewModel.platstypes, 
optionsText:'Nom',
optionsValue: 'TypeId',
value: TypeId">
</select>

这告诉 Knockout 您想要使用 platstypes 中的 TypeId 属性作为选项的值,并告诉它从platscuisines

中每个项目的 TypeId 属性

关于选择元素的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7516089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com