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

时间:2020-09-10 21:41:03

标签: asp.net asp.net-core razor entity-framework-core

学生出勤班

 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值时,即使选中也保持为假

1 个答案:

答案 0 :(得分:0)

由于表单中的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