when I run the code, I dont see the error message that Job Title is required.
However, I see the error message saying "First name is required". I also tried to put the bleow code in the controller:
I have the following code:
Model:
public partial class EmployeeInfo
{
[DisplayName("First Name")]
[Required(ErrorMessage = "First Name is required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Job Title is required.")]
[DisplayName("Job Title")]
public virtual JobTitleLookup JobTitleLookup { get; set; }
}
public class JobTitleLookup
{
public int JobTitleLookupId { get; set; }
public string Title { get; set; } = null!;
public virtual List<EmployeeInfo> EmployeeInfos { get; } = new List<EmployeeInfo>();
}
This is the controller:
public async Task<IActionResult> Index()
{
jobTitle = await _Reassign.GetJobTitle();
ViewData["Jobs"] = new SelectList(jobTitle, "JobTitleLookupId", "Title");
}
this is inside the service
public async Task<List<JobTitleLookup>> GetJobTitle()
{
return await _ackContext.JobTitleLookup.OrderBy(c => c.Title).ToListAsync();
}
this is the view:
<div class="col-md-4">
<label asp-for="JobTitleLookup" class="control-label" style="font-weight:bold;"></label>
<select asp-for="JobTitleLookup" class="form-control" asp-items="ViewBag.Jobs">
<option value="0">--Please select--</option>
</select>
<span asp-validation-for="JobTitleLookup" class="text-danger"></span>
</div>
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(EmployeeInfo info)
{
if (info.JobTitleLookupId ==null)
{
var validationMessage = "Job Title is required";
this.ModelState.AddModelError("JobTitleLookupId", validationMessage);
}
if (ModelState.IsValid)
{
}
return RedirectToAction(nameof(Index));
}
Still, I dont see the error message. Any help with this will be highly appreciated.