2011-09-22 10 views
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}] 

मैं एक के साथ एक मेज में मेरे सभी रिकॉर्ड प्रदर्शित करना चाहते हैं टाइप आईडी को सही मान में प्रारंभ करने के लिए चुनें।

यहाँ मेरी कोड है:

<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 संपत्ति का उपयोग करना चाहते अपने विकल्प और से platscuisines

में प्रत्येक आइटम की संपत्ति से फ़ील्ड के मान को पढ़ने/लिखने के लिए कहता है
संबंधित मुद्दे