检索mvc 5中复选框的值

时间:2017-12-21 05:31:52

标签: checkbox asp.net-mvc-5

我列出了每行的复选框,以标记学生的出勤率。我设法在数据库中插入复选框的值。但是,当我尝试编辑这些值时,从数据库中获取;对于每一行,检查类似id的复选框。虽然我根据索引值对复选框进行了标记,但没有区别。

User.cs

public string FirstName { get; set; }
public string LastName { get; set; }
public List<Models.Days> days { get;set;}

StudentAttendanceVM.cs

public Models.User user { get; set; }
public Models.StudentBatch studentbatch { get; set; }

Days.cs

public class Days
{
    public string dayid { get; set; }
    public string dayname { get; set; }
    public bool ischecked { get; set; }
}

Controller.cs

List<Models.Days> day = new List<Models.Days>();
for (int i = 0; i < TotalCheckBoxes; i++)
{
    day.Add(new Models.Days { dayid = Guid.NewGuid().ToString(), dayname = getdays[i], ischecked = false });
}

List<Models.StudentAttendance> studentattendance = new List<Models.StudentAttendance>();

foreach (Models.User lst in users)
{
    studentattendance.Add(new Models.StudentAttendance { studentbatch = new Models.StudentBatch  { batchId = id }, user = new Models.User { Id= lst.Id, FirstName = lst.FirstName, LastName = lst.LastName, days = day}});
}

List<string> attendance = contStudent.GetAttendance(id) // here I'm fetching result from database

if (attendance.Count > 0)
{
    string status = "";
    string status1 = "";

    for (int k = 0; k < attendance.Count; k++)
    {
        status = attendance[k].ToString();
        for (int i = 0; i < status.Length; i++)
        {
            status1 = status[i].ToString();
            if (status1 == "1")
            {
                studentattendance[k].user.days[i].ischecked = true; // here I'm trying to check the checkbox of particular index, but each item of the same index in studentattendance list gets checked.
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用

生成变量day
List<Models.Days> day = new List<Models.Days>();

然后将该实例(引用类型)分配给每个User

day只有一个实例,因此您对其所做的任何更改都会反映在每个User模型中。

您需要为每个List<Days>创建一个单独的User实例。

foreach (Models.User lst in users)
{
    // Move the code for initializing the collection of Days here
    List<Models.Days> day = new List<Models.Days>();
    for (int i = 0; i < TotalCheckBoxes; i++)
    {
        day.Add(new Models.Days { dayid = Guid.NewGuid().ToString(), dayname = getdays[i], ischecked = false });
    }
    studentattendance.Add(new Models.StudentAttendance
    {
        studentbatch = new Models.StudentBatch
        {
            batchId = id
        },
        user = new Models.User
        {
            Id= lst.Id,
            FirstName = lst.FirstName,
            LastName = lst.LastName,
            days = day
        }
    });
}