您可以使用带有 ajax 的引导模式对话框将详细信息/视图部分视图结果加载到模式对话框。
首先,为按钮添加一个新的 css 类,稍后我们将使用它来连接 click 事件以启动模态对话框。此外,我们将使用Url.Action html 帮助方法生成详细信息视图的 url,并将其保存在按钮的 html5 数据属性中(稍后我们将在 ajax 调用中使用它)
@foreach (var item in Model.Questions)
{
<tr>
<td>
<button type="button" class="btn btn-success btn-sm modal-link"
data-targeturl="@Url.Action("Details","Home",new { id = item.Id })">
View
</button>
</td>
</tr>
}
现在将以下代码添加到您当前的视图(甚至是布局)中。这将作为我们模式对话框的容器。
<!-- The below code is for the modal dialog -->
<div id="modal-container" class="modal fade" tabindex="-1" role="dialog">
<a href="#close" title="Close" class="modal-close-btn">X</a>
<div class="modal-content">
<div class="modal-body"></div>
</div>
</div>
现在,让我们在任何具有“modal-link”css 类的元素上连接click 事件。我们之前已将此类添加到我们的按钮中。
$(function () {
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$("#modal-container").remove();
$.get($(this).data("targeturl"), function (data) {
$('<div id="modal-container" class="modal fade">'+
'<div class="modal-content" id= "modalbody" >'+
data + '</div></div>').modal();
});
});
});
因此,当用户单击按钮时,它会读取 targeturl 数据属性的值(这是一个在查询字符串中具有项目 id 值的 URL)并对该 URL 进行 ajax 调用.在我们的例子中,它将调用Details 操作方法。所以让我们确保它返回部分视图结果(输出模态对话框内容)
public ActionResult Details(int id)
{
// Get the data using the Id and pass the needed data to view.
var vm = new QuestionViewModel();
var question = db.Questions.FirstOrDefault(a=>a.Id==id);
// To do: Add null checks
vm.Id = question.Id;
vm.Title = question.Title;
vm.Description = question.Description;
return PartialView(vm);
}
局部视图将具有模态对话框所需的 html 标记。
@model YourNameSpace.QuestionViewModel
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<h4>@Model.Title</h4>
<p>@Model.Description</p>
<p>Some other content for the modal </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>