I recommend changing the view model design which makes the standard model validation easier.
Create a view model that defines the post parameters sent to the post action and include the input validation attributes.
public class EmployeeInfoViewModel
{
[DisplayName("First Name")]
[Required(ErrorMessage = "First Name is required")]
public string FirstName { get; set; } = string.Empty;
[Required(ErrorMessage = "Job Title is required.")]
[DisplayName("Job Title")]
public int? JobTitleId { get; set; }
}
Create the view that matches the view model properties.
@model EmployeeInfoViewModel
@{
ViewData["Title"] = "Job Title Example";
}
<div class="container">
<form method="post">
<div>
<label asp-formaction="FirstName" class="control-label" style="font-weight:bold;"></label>
<input asp-for"FirstName" />
</div>
<div>
<label asp-for="JobTitleId" class="control-label" style="font-weight:bold;"></label>
<select asp-for="JobTitleId" class="form-control" asp-items="ViewBag.Jobs">
<option value="">--Please select--</option>
</select>
<span asp-validation-for="JobTitleId" class="text-danger"></span>
</div>
<div>
<input type="submit" value="submit" />
</div>
</form>
</div>
Populate a List<SelectListItem>with the job titles. Pass the job titles (select options) using the ViewBag.
public class JobTitleController : Controller
{
[HttpGet]
public IActionResult Index()
{
ViewBag.Jobs = PopulateOptions();
return View();
}
[HttpPost]
public IActionResult Index(EmployeeInfoViewModel model)
{
ViewBag.Jobs = PopulateOptions();
return View();
}
private List<SelectListItem> PopulateOptions()
{
List<SelectListItem> options = new List<SelectListItem>()
{
new SelectListItem()
{
Text = "Job Title 1",
Value = "1"
},
new SelectListItem()
{
Text = "Job Title 2",
Value = "2"
},
new SelectListItem()
{
Text = "Job Title 3",
Value = "3"
}
};
return options;
}
}
The official tutorials and documentation covers these concepts.
https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/?view=aspnetcore-9.0
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-9.0