即使在asp.net核心剃刀页面中选中,复选框列表也返回false

问题描述

学生出勤班

 public class StudentAttendance
{
    public int Id { get; set; }
    public int StudentID { get; set; }
    public bool IsPresent { get; set; }

}

查看我的出勤表表格

 @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> }

出勤页面模型

 [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; }

出席Post()

foreach (var id in HiddenID)
        {
            Conn.StudentAttendance.Add(new StudentAttendance
            {
                StudentID = id,IsPresent = IsPresent,});
        }

当我提交并保存IsPresent值时,即使选中也保持为假

解决方法

由于表单中的IsPresent未绑定到模型,并且模型中IsPresent的默认值为false。最后,它每次都获得假。通过使用JavaScript函数动态更改复选框中的值,可以将相应的选定ID提交到后台。

在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>
}

然后,在post方法中,获取已检查的ID,并说明是否已检查ID。

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,});*/
            }
        }

结果:

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...