2011-09-22 34 views
7

selectを初期値で初期化したいと思います。私は型IDの配列は次のように宣言した要素の初期値を選択

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

:私は、JSONオブジェクトは、このいずれかのように私のバックエンドから戻ってきた私は、テーブル内のすべての私のレコードを表示したいと思い

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

答えて

12

あなたはあなたの選択などを書きたいでしょう:

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

これはあなたのための値としてplatstypesからTypeIdプロパティを使用することをノックアウトを伝えます各項目のTypeIdプロパティからフィールドの値を読み書きするように指示します。platscuisines