To get all Courses checked and unchecked in the Edit(Get) view, I used a ViewModel class and assigned all courses from database in a variable and reassigned this variable with Another ViewModel property send in the Edit View. It works fine. But After Editing items, while Posting in to the Edit(POST) action, The ViewModel property is getting Null and an exception is throwing:
"System.NullReferenceException: Object reference not set to an instance of an object."
I am providing my Code to all:
My Edit(GET) Action:
public ActionResult Edit(int id)
{
var st = db.Students.FirstOrDefault(s => s.StudentId == id);
//CheckBoxItemVM is another ViewModel
var allCourses = db.Courses.Select(x => new CheckBoxItemVM()
{
Id = x.CourseId,
Title = x.CourseName,
IsChecked = x.StudentCourses.Any(c => c.StudentId == st.StudentId) ? true : false
}).ToList();
StudentViewModel vm = new StudentViewModel();
vm.StudentName = st.StudentName;
vm.Country = st.Country;
vm.EditCourses = allCourses; // this data is availabe for Editing in the view
return View(vm);
}
//This is a ViewModel that is not from my Database
public class CheckBoxItemVM
{
public int Id { get; set; }
public string Title { get; set; }
public bool IsChecked { get; set; }
}
//This is the part of the view where I am sending allCourses
<div class="form-group">
@Html.LabelFor(model => model.CourseId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
// While GET, Data is fine in Model.EditCourses
@foreach (var item in Model.EditCourses) //Error Shows here while "POST", this shows Null
{
@Html.HiddenFor(model => item.Id)
@Html.CheckBoxFor(model => item.IsChecked)
@Html.DisplayFor(model => item.Title)
}
</div>
</div>
// After Editing and Posting, EditCourses in vm is getting null
[HttpPost]
public ActionResult Edit(StudentViewModel vm, Student student,StudentCourse sc)
{
try
{
List<StudentCourse> studentCourse = new List<StudentCourse>();
student.StudentName = vm.StudentName;
student.Country = vm.Country;
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
int studentId = student.StudentId;
if (vm.EditCourses!=null)
{
foreach (var item in vm.EditCourses)
{
if (item.IsChecked == true)
{
studentCourse.Add(new StudentCourse()
{
StudentId = studentId,
CourseId = item.Id
});
}
}
}
var currentStudentCourses = db.StudentCourses.Where(x => x.StudentId == studentId).ToList();
var oldStudentCourse = currentStudentCourses.Except(studentCourse).ToList();
foreach (var item in oldStudentCourse)
{
db.StudentCourses.Remove(item);
db.SaveChanges();
}
var ifAnyCourse = db.StudentCourses.Where(t => t.StudentId == studentId).ToList();
foreach (var item in studentCourse)
{
if (!ifAnyCourse.Contains(item))
{
db.StudentCourses.Add(item);
db.SaveChanges();
}
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
How to set an Instance of vm.EditCourses or Model.EditCourses? I tried a lot. Please help me out!