确实有两种可能性:有或没有 AJAX。如果您想在没有 AJAX 的情况下执行此操作,您可以订阅“编辑”链接的单击事件,然后将值从表复制到模式,最后显示模式。
因此,首先给您的编辑链接一些类别:
<a href="#" class="btn edit">Edit</a>
您可以订阅:
$('a.edit').on('click', function() {
var myModal = $('#myModal');
// now get the values from the table
var firstName = $(this).closest('tr').find('td.firstName').html();
var lastName = $(this).closest('tr').find('td.lastName').html();
....
// and set them in the modal:
$('.firstName', myModal).val(firstName);
$('.lastNameName', myModal).val(lastName);
....
// and finally show the modal
myModal.modal({ show: true });
return false;
});
这假设您已经为<td>
模式中的元素和输入字段。
如果您想使用 AJAX,您可以生成如下链接:
@Html.ActionLink("Edit", "Edit", "Employees", new { id = employee.Id }, new { @class = "btn edit" })
然后订阅该按钮的点击事件并触发AJAX请求:
$('a.edit').on('click', function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(result) {
$('#myModal').html(result).find('.modal').modal({
show: true
});
}
});
return false;
});
您的主视图中将有一个简单的模式占位符,其中包含详细信息:
<div id="myModal"></div>
将要执行的控制器操作应使用 id 获取员工记录并将其传递给部分视图:
public ActionResult Edit(int id)
{
Employee employee = repository.Get(id);
EmployeeViewModel model = Mapper.Map<Employee, EmployeeViewModel>(employee);
return PartialView(model);
}
最后是相应的部分:
@model EmployeeViewModel
<div class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Edit Employee</h3>
</div>
<div class="modal-body">
<div>
@Html.LabelFor(x => x.FirstName)
@Html.EditorFor(x => x.FirstName)
</div>
<div>
@Html.LabelFor(x => x.LastName)
@Html.EditorFor(x => x.LastName)
</div>
...
</div>
<div class="modal-footer">
<a href="#" class="btn btn-primary" data-dismiss="modal">Close</a>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
显然,您还需要将输入字段包装到Html.BeginForm
这将允许您将员工的更新详细信息发送到服务器。如果您想留在同一页面上,可能还需要 AJAX 化此表单。