You're not populating the
ViewBag
collections used in your view. Either the tutorial you're following hasn't got to that part yet, or it's not a good tutorial.
Create a method in your controller to populate the lookups, and call it before displaying the view.
private void PopulateLookups(ProjectRole role)
{
var projects = _context.Projects.OrderBy(p => p.Name).ToList();
ViewBag.ProjectId = projects.Select(p => new SelectListItem
{
Value = p.Id.ToString(),
Text = p.Name,
Selected = p.Id == role.ProjectId,
});
var people = _context.People.OrderBy(p => p.LastName).ThenBy(p => p.FirstName).ToList();
ViewBag.PersonId = people.Select(p => new SelectListItem
{
Value = p.Id.ToString(),
Text = $"{p.LastName}, {p.FirstName} {p.MiddleName}",
Selected = p.Id == role.PersonId,
});
}
[HttpGet]
public IActionResult Create()
{
ProjectRole model = new ProjectRole();
PopulateLookups(model);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,HourlyRate,PersonId,ProjectId,RoleId")] ProjectRole projectRole)
{
if (ModelState.IsValid)
{
_context.Add(projectRole);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
PopulateLookups(projectRole);
return View(projectRole);
}
The Select Tag Helper | Tag Helpers in forms in ASP.NET Core | Microsoft Docs[
^]