2

選択したアイテムの情報(プロパティ)でテキストボックスを更新しようとしています。Id の代わりに選択した項目名を取得できますか、つまり、項目を選択したときに JavaScript で ViewData の whats のプロパティを取得し、それを txtbox に設定するにはどうすればよいですか?

         @Html.ListBox("ListBoxName", new SelectList((IEnumerable<Epic>)ViewData["selectedestimate"], "Id", "Name", "EstimatedTime"), new {@class = "ListBoxClass", @style = "height: 325px;"})
        @Html.TextBoxFor(model => model.Name, new {@class = "TimeClass"})



   <script type="text/javascript">
         $(function () {
           $(".ListBoxClass").click(function (event) {
        var selectedid = $(this).find("option:selected").val();

         // get items properties and info so that the value can be set to a textbox
        //set textbox value to Name of selected Value
        $(".TimeClass").val(selectedid);
        event.preventDefault(); // Stop the browser from redirecting as it normally would
        $.get('@Url.Action("UserStoriesList", "Estimate")', { id: selectedid }, function (result) {
            $('#stories').html(result);
        });
    });
});
    </script> 
4

1 に答える 1

3

ListBox は、複数の項目を選択できる点を除いて、DropDownList に似ています。同じ HTML タグ ( <select>) を使用しますが、属性を追加しmultipleます。したがって、マークアップをレンダリングすると、次のようになります。

<select id="ListBoxName" name="ListBoxName" multiple="multiple">
    <option value="id1">text 1</option>
    <option value="id2">text 2</option>
    <option value="id3">text 3</option>
    ...
</select>

ご覧のとおり、ID とテキストに関する情報が DOM 内にあります。選択したアイテムに関する他の情報を取得したい場合は、AJAX リクエストをサーバーに送信し、選択した ID を渡して取得する必要があります。したがって、テキストのみを表示したい場合:

$(function() {
    ​$('.ListBoxClass option')​.click(function() {
        if ($(this).is(':selected')) {
            var selectedId = $(this).val();
            var selectedText = $(this).text();
            $('.TimeClass').val(selectedText);
            ...
        }
    });​
});

clickハンドラーは、ユーザーがリストボックス内の要素をクリックするたびに実行されますが、if 条件はユーザーがアイテムを選択した場合にのみ満たされます。

于 2012-04-14T06:41:28.177 に答える