您会发现使用 jQuery ajax 方法比使用 Ajax.ActionLink() 和 Ajax.BeginForm() 方法更容易。在主视图中
<button type="button" class="details" data-id="Model.UserName">View details</button>
<div id="content"></div>
var detailsUrl = '@Url.Action("Details", "User")';
var editUrl = '@Url.Action("Edit", "User")';
// Display the details view
$('.details').click(function() {
$.get(detailsUrl, { id: $(this.data('id') }, function(response) {
$('#content').html(response);
});
});
// Display the edit view
$('#content').on('click', '#edit', function() {
$.get(editUrl, { id: $(this.data('id') }, function(response) {
$('#content').html(response);
});
});
// Post the edit form and replace with the updated details view
$('#content').on('click', '#save', function() {
var id = $(this).data('id');
var data = $(this).closest('form').serialize();
$.post(editUrl, data, function(response) {
if (response) {
$.get(detailsUrl, { id: id }, function() {
$('#content').html(response);
});
} else {
// Oops
}
}).fail(function (result) {
// Oops
});
});
以上假设UserController具有以下方法
public PartialViewResult Details(int ID) // or string?
{
// Get the user model based on the ID
return PartialView("_Details", model);
}
public PartialViewResult Edit(int ID) // or string?
{
// Get the user model based on the ID
return PartialView("_Edit", model);
}
public JsonResult Edit(UserModel model) // replace with the name of your model
{
// Save the model
return Json(true); // indicate success
}
部分视图在哪里
_Details.cshtml
@model UserModel
.... // display properties of the model
<button type="button" id="edit" data-id="Model.UserName">Edit</button>
_Edit.cshtml
@model UserModel
<form>
.... // controls for properties of the model
<button type="button" id="save" data-id="Model.UserName">Save</button>
</form>