2011-09-22 36 views
7

Tôi muốn khởi tạo một select với giá trị ban đầu. Tôi đã một đối tượng JSON trở về từ backend của tôi như thế này một:Chọn giá trị ban đầu của phần tử

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

Tôi đã một mảng của typeIds tuyên bố như thế này:

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

Tôi muốn hiển thị tất cả hồ sơ của tôi trong một bảng với một chọn cho typeId được khởi tạo với giá trị chính xác.

Đây là mã của tôi:

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

Trả lời

12

Bạn sẽ muốn viết bạn chọn như:

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

này cho Knockout mà bạn muốn sử dụng TypeId tài sản từ platstypes làm giá trị cho bạn tùy chọn và yêu cầu nó đọc/ghi giá trị của trường từ thuộc tính TypeId của từng mục trong platscuisines

Các vấn đề liên quan