2

Bootstrap modalを持っています。これは、それぞれ別の ID を提供するさまざまなハイパーリンクから起動できます。

しかし、私が望むのは、モーダルが起動されるたびに、モーダルに渡された ID のデータが取り込まれることです。(簡略化された)コードは次のとおりです(説明については、コード内のコメントを参照してください)。

@model ViewModels.BookcaseItem.EditBookcaseItemViewModel

<div class="modal hide modal-large" id="editBookDialog">
    @using (Html.BeginForm("Edit", "Bookcase", FormMethod.Post, new { @class = "form-horizontal" }))
    {
        <!-- this is where the ID will be passed to -->
        @Html.HiddenFor(x => x.Id)

        <div class="modal-body">
            <!-- there's actually a couple of editors and labels here, but that doesn't really matter -->
            @Html.EditorFor(x => x.Bla)
        </div>
        <div class="modal-footer">
            <a href="#" class="btn" data-dismiss="modal">Close</a>
            <input type="submit" value="Save" class="btn btn-primary" />
        </div>
    }
</div>

モーダルを起動して ID を渡すために使用されるハイパーリンクの 1 つを次に示します。

<a href="#editBookDialog" data-toggle="modal" data-id="@bookcaseItem.Id" title="Edit this item" class="open-EditBookDialog"></a>

最後になりましたが、実際に ID を渡すための JQuery 部分:

$(document).on("click", ".open-EditBookDialog", function () {
    var myBookcaseItemId = $(this).data('id');
    $(".modal #Id").val(myBookcaseItemId);
    $('#editBookDialog').modal('show');
});

そして、モーダルが配置されている PartialView にデータを返す署名 ActionResult Edit(string id) を持つメソッドがあると仮定しましょう。

モーダルはすべてのハイパーリンクを含むページに既に埋め込まれていますが、デフォルトでは表示されません。

渡されたIDに基づいて異なるデータを入力する方法がわかりません。

4

1 に答える 1

2

コントローラー アクションを使用して、サーバーから新しいデータをロードするために AJAX を使用できます。

$(function() {
    $(document).on('click', '.open-EditBookDialog', function () {
        var myBookcaseItemId = $(this).data('id');
        // send an AJAX request to fetch the data
        $.get(this.href, { id: myBookcaseItemId }, function(data) {
            $('#editBookDialog').html(data).modal('show');
        });
        return false;
    });
});

明らかに、ダイアログを開くはずのアンカーを変更して、 href がコントローラーの編集アクションを指すようにする必要があります。

@Html.ActionLink(
    "Some text", 
    "Edit", 
    null, 
    new {
        data_toggle = "modal",
        data_id = bookcaseItem.Id,
        title = "Edit this item",
        @class = "open-EditBookDialog"
    }
)
于 2012-05-24T06:14:22.553 に答える