我有一个“待办事项列表”,其中任务(任务)作为记录存储在数据库中。 Assignment
模型中的元素之一是Complete
。该页面使用for循环输出Assignments
(List<Assignment>
)表中的所有值,并在最后显示一个复选框。
@using (var ctx = new AssignmentContext())
{
var assignmentList = ctx.Assignments.ToList();
foreach (Assignment assignment in assignmentList)
<tr name ="@assignment.AssignmentId">
<td>@assignment.CourseName</td>
<td>@assignment.AssignmentName</td>
<td>@assignment.DueDate</td>
<td>@assignment.Value</td>
<td>@Html.CheckBox()</td>
</tr>
}
我想通过单击复选框来更改数据库中bool Assignment.Complete
的状态。我对Web开发非常陌生,HTML和C#的混合使我感到困惑。我该如何onClick
调用一个控制器函数,当我这样做时,如何在for循环已经运行之后如何将其传递给特定行。我需要JS吗?
答案 0 :(得分:2)
尝试: CsHtml:
@using (var ctx = new AssignmentContext())
{
var assignmentList = ctx.Assignments.ToList();
foreach (Assignment assignment in assignmentList)
<tr name ="@assignment.AssignmentId">
<td>@assignment.CourseName</td>
<td>@assignment.AssignmentName</td>
<td>@assignment.DueDate</td>
<td>@assignment.Value</td>
<td>@Html.CheckBox(assignment.AssignmentId, assignment.Complete, new {@id= assignment.AssignmentId,onclick= "complete($(this))" })</td>
</tr>
}
Java脚本:
<script>
function complete(selector) {
var assignmentId = selector.attr('id');
$.get('/Assignment/Complete', { id: assignmentId, checked: selector.checked}, function() {
alert('successfull')
})
}
</script>
控制器:
public async Task<JsonResult> Complete(int id,bool checked)
{
@using(var ctx = new AssignmentContext())
{
var assignment = ctx.Assignments.Find(id);
assignment.Complete = checked;
ctx.SaveChanges();
}
return Json(new { isSuccess =true }, JsonRequestBehavior.AllowGet);
}