问题
I've got a Bootstrap modal, that can be launched from different hyperlinks, each supplying another ID.
But what I want is that every time the modal is launched, it is populated with the data for the ID that's passed to the modal. Here's the (simplified) code (see the comments inside the code for explanation):
@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>
Here is one of the hyperlinks that is used to launch the modal and pass the ID to it:
<a href="#editBookDialog" data-toggle="modal" data-id="@bookcaseItem.Id" title="Edit this item" class="open-EditBookDialog"></a>
And last but not least the JQuery part to actually pass the ID:
$(document).on("click", ".open-EditBookDialog", function () {
var myBookcaseItemId = $(this).data('id');
$(".modal #Id").val(myBookcaseItemId);
$('#editBookDialog').modal('show');
});
And let's assume there's a method with the signature ActionResult Edit(string id) that returns the data to the PartialView where the modal is placed in.
The modal is already embedded in the page with all the hyperlinks, it's just not visible by default.
I just can't figure out how to populate it with different data based on the ID that was passed.
回答1:
You could use AJAX in order to load fresh data from the server by going through the controller action:
$(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;
});
});
Now obviously you should modify the anchor that is supposed to open the dialog so that it's href points to the Edit controller action:
@Html.ActionLink(
"Some text",
"Edit",
null,
new {
data_toggle = "modal",
data_id = bookcaseItem.Id,
title = "Edit this item",
@class = "open-EditBookDialog"
}
)
来源:https://stackoverflow.com/questions/10728625/bootstrap-modal-load-data-for-supplied-id