2011-09-22 25 views
7

Vorrei inizializzare uno select con un valore iniziale. Ho un oggetto JSON tornato dalla mia backend come questo:Selezionare il valore iniziale dell'elemento

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

Ho una serie di typeIds dichiarato come questo:

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

Vorrei potrai vedere tutti i miei record in una tabella con un selezionare per il tipo ID inizializzato sul valore corretto.

Ecco il mio codice:

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

risposta

12

Si consiglia di scrivere il vostro selezionare come:

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

Questo dice Knockout che si desidera utilizzare la proprietà TypeId dal platstypes come il valore per il vostro opzioni e dice di leggere/scrivere il valore del campo dalla proprietà TypeId di ogni articolo in platscuisines

Problemi correlati