0

私は多くのもの (Rails、Backbone.JS、HTML) を使用していますが、select で選択した値をロードする方法がわかりません。私は「編集」フォームにいて、サーバー (Rails API) から情報をロードし、選択したオプションをフォームにロードしたいと考えています。Rails には select タグのヘルパーがありますが、jst.eco ファイルを使用していて、サーバーからデータをロードする方法がわかりません。

4

1 に答える 1

0

これが「a」の方法です。テンプレートを定義します。

<script type="text/template" id="category_options_template">
    <select id="CategoryId" name="CategoryId">
        <% _(categories).each(function(c) { %>
            <% if (c.get('IsSelected') == "selected") { %>
                <option value="<%= c.get('CategoryId') %>" selected="selected"><%- c.get('CategoryName') %></option>
        <% } %>
            <% if (c.get('IsSelected') == "") { %>
                <option value="<%- c.get('CategoryId') %>" id="<%- c.get('CategoryName') %>"><%- c.get('CategoryName') %></option>
        <% } %>
        <% }); %>
    </select>
</script>

ドロップダウンボックスに入るはずのアイテムを取得して、配列に保存します。例:

var categories = new Array();
function fetch_categories() {
     $.ajax({
            url: '/GetCategories',
            dataType: "json",
            success: function (data) {
                for (i = 0; i < data.length ; i++) {
                    categories[i] = new category_model({
                        CategoryId: data[i].CategoryId,
                        CategoryName: data[i].CategoryName,
                    });
                }
            },
            error: function (data) {
                console.log('Error');
            }
        });
    }

var category_model;
function setup_category_model() {
        product_category_model = Backbone.Model.extend({
            idAttribute: 'CategoryId',
            defaults: {
                CategoryId: null,
                CategoryName: null,
                IsSelected: "",
            },
            urlRoot: '/Categories',
        });
    }

init 中にモデルが渡されたビューの render 関数では、次のようになります。

var x = this.model.get('CategoryId');
for (i = 0; i < categories.length; i++) {
    categories[i].set('IsSelected', "");

    if (x && x == categories[i].get('CategoryId')) {
        categories[i].set('IsSelected', "selected");
    }
}
var categories_view = _.template($("#category_options_template").html(), {
    categories: categories,
    labelValue: 'Categories'
});
于 2013-06-09T08:00:30.217 に答える