This is my view
@model MyProject.ViewModel.CourseViewModel
@{
ViewData["Title"] = "AddCourseView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Add Course</h1>
<div class="row">
<div class="col-md-12">
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Course.CourseName"></label>
<input asp-for="Course.CourseName" class="form-control" />
<span asp-validation-for="Course.CourseName" class="text-danger"></span>
</div>
<label>Select lecturers to the course</label>
@{
var lst = Model.List;
@for (int i = 0; i<lst.Count(); i++)
{
var lecturer = lst.ElementAt(i);
<div class="checkbox">
<label><input type="checkbox" value="" id="checkbox @i" [email protected]>@lecturer.LecturerId</label>
</div>
}
@if (lst.Count() == 0)
{
<div class="checkbox">
<span class="badge badge-danger" style="font-size:medium">Lecturers list is empty</span>
</div>
}
}
<p></p>
<button type="submit" class="btn btn-primary">Create</button>
</form>
</div>
</div>
The view call AddCourse
This is my controller:
[HttpGet]
public IActionResult AddCourse()
{
var lst = userService.GetAllLecturers();
CourseViewModel courseViewModel = new CourseViewModel();
courseViewModel.List = new List<IsCheckedLecturer>();
foreach(var lecture in lst)
{
courseViewModel.List.Add(new IsCheckedLecturer
{
IsChecked = false,
LecturerId = lecture.UserId
});
}
return View(courseViewModel);
}
[HttpPost]
public IActionResult AddCourse(CourseViewModel viewModel)
{
return View(viewModel);
}
HttpGet work fine, but the HttpPost method(the second method) get a null list instead of get the model from the view(by model binding)
This is the courseViewModel
public class CourseViewModel
{
public Course Course { get; set; }
public IList<IsCheckedLecturer> List { get; set; }
}
public class IsCheckedLecturer
{
public bool IsChecked { get; set; }
public string LecturerId { get; set; }
}
why doesn't model binding work? and how i fix it? Maybe because its complex view model?