假设您的 TaskList 部分视图如下:
<table>
<tr>
<th>
TaskCol1
</th>
<th>
TaskCol2
</th>
<th>
TaskCol3
</th>
<th>
TaskCol4
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TaskCol1)
</td>
<td>
@Html.DisplayFor(modelItem => item.TaskCol2)
</td>
<td>
@Html.DisplayFor(modelItem => item.TaskCol3)
</td>
<td>
@Html.DisplayFor(modelItem => item.TaskCol4)
</td>
<td>
@Html.HiddenFor(modelItem => item.TaskId)
</td>
</tr>
}
</table>
而您的 TaskDetail 部分视图:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Task</legend>
@Html.HiddenFor(model => model.TaskId)
<div class="editor-label">
@Html.LabelFor(model => model.TaskCol1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.TaskCol1)
@Html.ValidationMessageFor(model => model.TaskCol1)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.TaskCol2)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.TaskCol2)
@Html.ValidationMessageFor(model => model.TaskCol2)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.TaskCol3)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.TaskCol3)
@Html.ValidationMessageFor(model => model.TaskCol3)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.TaskCol4)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.TaskCol4)
@Html.ValidationMessageFor(model => model.TaskCol4)
</div>
</fieldset>
}
您可以通过 ajax 处理调用服务器端方法的表格行的单击事件:
$(function () {
$("tr").click(function () {
var itemId = $("input[type='hidden']", this).val();
$.getJSON("/Home/GetDetails", { id: itemId }, function (data) {
$("#TaskId").val(data.TaskId);
$("#TaskCol1").val(data.TaskCol1);
$("#TaskCol2").val(data.TaskCol2);
$("#TaskCol3").val(data.TaskCol3);
$("#TaskCol4").val(data.TaskCol4);
});
});
});
最后,您的控制器必须具有以下方法:
public ActionResult GetDetails(int id)
{
TaskEntities entities = new TaskEntities();
var item =
(from t in entities.Tasks
where t.TaskId == id
select t).FirstOrDefault();
return Json(item, JsonRequestBehavior.AllowGet);
}