Student Attendance class
public class StudentAttendance
{
public int Id { get; set; }
public int StudentID { get; set; }
public bool IsPresent { get; set; }
}
View table for my attendance form
@foreach (var student in Model.Students)
{
<tr>
<td> @student.FullName</td>
<td><input type="hidden" asp-for="HiddenID" id="id" value="@student.StudentID"/></td>
<td ><label class="col-form-label"><input type="checkbox" name="IsPresent" ></label></td> </tr> }
Attendance Page Model
[BindProperty]
public StudentAttendance studentAttendance { get; set; }
[BindProperty]
public List<int> StudentAttendanceList { get; set; }
[BindProperty(SupportsGet = true)]
public int? SearchClassID { get; set; }
[BindProperty]
public List<int> HiddenID { get; set; }
[BindProperty]
public bool IsPresent { get; set; }
public IEnumerable<Student> Students { get; set; }
Attenadance On Post()
foreach (var id in HiddenID)
{
Conn.StudentAttendance.Add(new StudentAttendance
{
StudentID = id,
IsPresent = IsPresent,
});
}
When i submit and save the IsPresent value remains false even when checked
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Since the IsPresent in the form is not bound to the Model, and the default value of IsPresent in the model is false. Finally, it obtained false each time. By dynamically changing the value in the checkbox through a JavaScript function, the corresponding selected id can be submitted to the background.
In Attendance.cshtml
<form method="post">
<table>
@foreach (var student in Model.Students)
{
<tr>
<td> @student.FullName </td>
<td><input type="hidden" asp-for="HiddenID" id="id" value="@student.StudentID" /></td>
<td>
<label class="col-form-label">
<input type="checkbox" id="IsPresent" name="isPresent" value="false" onchange="changePresent(event,@student.StudentID)">
</label>
</td>
</tr>
}
</table>
<input type="submit" name="name" value="sub" />
</form>
@section Scripts{
<script>
function changePresent(e,id) {
if (e.target.value=='true') {
e.target.value = false
}
else {
console.log('-=-=')
e.target.value = id
}
}
</script>
}
Then, in post method, get the checked id, and justify whether the id is checked.
public void OnPost(int[] isPresent)
{
foreach (var id in HiddenID)
{
new StudentAttendance
{
StudentID = id,
IsPresent = id == isPresent[id - 1],
};
/*Conn.StudentAttendance.Add(new StudentAttendance
{
StudentID = id,
IsPresent = IsPresent,
});*/
}
}
result:
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
