Not sure why but the for some reason the view model is not binding the DepartmentId
when I hit the submit button, I get an error:
Value cannot be null.
Parameter name: valueDescription: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Not sure which value is being null as the code does not break, rather after hitting the submit button that is the message that is being displayed.
I’m assuming it’s the departmentId
that’s not being properly bound to the DepartmentID property in CoursePreReqViewModel.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: value
View:
@using (Html.BeginForm("Catalog", "Courses", FormMethod.Post, new { @class = "pure-form pure-form-aligned" }))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col">
<input id="myInput" class="form-control" type="text" placeholder="Search..">
</div>
<div class="col">
@Html.LabelFor(model => model.DepartmentId, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model => model.DepartmentId, Model.DepartmentList, "Department", new { @class = "form-control required", id = "department-list" })
@Html.ValidationMessageFor(model => model.DepartmentId)
</div>
<div class="col">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
}
Controller:
[HttpPost]
public ActionResult Catalog(CoursePreReqViewModel viewModel)
{
DepartmentRepo dRepo;
CoursesRepo cRepo;
MajorPreRequisitesRepo reqRepo;
using (context)
{
dRepo = new DepartmentRepo(context);
cRepo = new CoursesRepo(context);
viewModel.PopulateDepermentSelectList(dRepo.GetAllDepartments());
reqRepo = new MajorPreRequisitesRepo(context);
viewModel.Courses = cRepo.GetAllCoursesAndPreReqsByDepartment(viewModel.DepartmentId);
}
return View(viewModel);
}
View model:
public class CoursePreReqViewModel
{
[Required]
[Display(Name = "")]
public int DepartmentId { get; set; }
public IList<Course> Courses { get; set; }
public IList<MajorPreRequisite> CoursesAndPreReqs { get; set; }
[Display(Name = "Department: ")]
public IList<Department> Departments { get; set; }
public CoursePreReqViewModel() { }
public SelectList DepartmentList
{
get
{
return new SelectList(Departments, "Id", "Name");
}
}
public void PopulateDepartmentSelectList(IList<Department> populatedDepartments)
{
Departments = populatedDepartments;
}
}
2
Answers
I can help you keep the code you have, and answer your question.
controller/classes:
view:
Sarthak here is another answer: this is the asp.net mvc fiddler https://dotnetfiddle.net/ARdtvr
!!!Display Name needs to be a value!!!