Reputation: 334
I have a list of checkboxes for every row to mark attendance of the students. I managed to insert values of the checkboxes in the database. However when i try to edit those values, fetched from the database; for every row checkboxes of similar id's gets checked. Although I'm marking check to checkboxes according to the index values, yet no difference was made.
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.
}
}
}
}
Upvotes: 0
Views: 233
Reputation:
Your generating the variable day
using
List<Models.Days> day = new List<Models.Days>();
and then assigning that instance (a reference type) to each User
.
There is only one instance of day
so any change you make to it is reflected in every User
model.
You need to make a separate instance of List<Days>
for each 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
}
});
}
Upvotes: 1