您应该使用局部视图。我使用以下方法:
使用视图模型,这样就不会将域模型传递给视图:
public class EditPersonViewModel{ public int Id { get; set; } // this is only used to retrieve record from Db public string Name { get; set; } public string Age { get; set; }}在你的
PersonController:
[HttpGet] // this action result returns the partial containing the modalpublic ActionResult EditPerson(int id){ var viewModel = new EditPersonViewModel(); viewModel.Id = id; return PartialView("_EditPersonPartial", viewModel);}[HttpPost] // this action takes the viewModel from the modalpublic ActionResult EditPerson(EditPersonViewModel viewModel){ if (ModelState.IsValid) { var toUpdate = personRepo.Find(viewModel.Id); toUpdate.Name = viewModel.Name; toUpdate.Age = viewModel.Age; personRepo.InsertOrUpdate(toUpdate); personRepo.Save(); return View("Index"); }}接下来,创建一个名为的局部视图
_EditPersonPartial。其中包含模态页眉,正文和页脚。它还包含Ajax表单。它是强类型的,并包含在我们的视图模型中。
@model Namespace.ViewModels.EditPersonViewModel<div ><button type="button" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Edit group member</h3></div><div>@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post, new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", UpdateTargetId = "list-of-people" })){ @Html.ValidationSummary() @Html.AntiForgeryToken() <div > @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name) @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age) </div> <div > <button type="submit">Save</button> </div>}现在在您的应用程序中的某处,说另一个_peoplePartial.cshtml等:
<div> @foreach(var person in Model.People) { <button data-id="@person.PersonId">Edit</button> }</div>// this is the modal definition<div id="edit-person"> <div id="edit-person-container"></div></div> <script type="text/javascript"> $(document).ready(function () { $('.edit-person').click(function () { var url = "/Person/EditPerson"; // the url to the controller var id = $(this).attr('data-id'); // the id that's given to each button in the list $.get(url + '/' + id, function (data) { $('#edit-person-container').html(data); $('#edit-person').modal('show'); }); }); }); </script>


