我在MVC视图中有一个表,显示员工的详细信息.我想添加编辑功能,但是不要在新页面中打开它,而是要使用引导模式显示它. (
http://twitter.github.com/bootstrap/javascript.html#modals)
我不认为我必须使用ajax,因为数据已经在页面上可用了.我想我需要一些jquery或者剃刀代码将所选员工的数据传递给引导模式,并将其弹出在同一个屏幕上.以下是我的代码任何帮助将不胜感激.谢谢
@Foreach(var item in Model.Employees) { <tr> <td>@User.Identity.Name </td> <td>@item.FirstName </td>....other columns <td><a href="#myModal" role="button" class="btn" data-toggle="modal">Edit</a> <td> </tr>........other rows } **Bootstrap Modal** <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Edit Employee</h3> </div> <div class="modal-body"> <p>Selected Employee details go here with textBox,dropdown,etc...</p> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> <button class="btn btn-primary">Save changes</button> </div> </div>
解决方法
确实有两种可能性:有或没有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; });
这假设您已经将适当的CSS类提供给< td>元素和您的模态中的输入字段.
@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中,这将允许您将更新的员工的详细信息发送到服务器.如果您想保持在同一页面,也可能需要AJAXify此表单.