开发者

Select element's initial value

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, ....}]

I have an array of typeIds declared like this :

[{ Nom: "Plats", TypeId: 0 },
 { Nom: "Crudités", TypeId: 1 },
 { Nom: "Tartes Salées", TypeId: 2}]

I would like to display all my records in a table with a select for the typeId initialized to the correct value.

Here is my code:

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


You would want to write your select like:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜