I have the following property in my Model class:
public partial class IndividualNomination
{
public int EmploeeId { get; set; }
[DisplayName("Name (First and Last)")]
[Required]
public string? EmployeeNumber { get; set; } = null!;
public int? JobTitleLookupId { get; set; }
}
EmployeeNumber is a required field. This is how I am populating EmployeeNumber field in the controller:
public IActionResult Create()
{
var UserName = HttpContext.User.Identity.Name;
employee = _lookupData.GetEmployeeLookup();
ViewData["employee"] = new SelectList(employee, "EmployeeNumber", "Name");
return View();
}
This is what I have in my .cshtml file:
<form asp-action="Create">
<div class="form-group row">
<div class="col-md-6">
<label asp-for="EmployeeNumber" class="control-label required"></label>
<select asp-for="EmployeeNumber" class="form-control" asp-items="ViewBag.employee">
<option value="0">--Select Employees--</option>
</select>
<span asp-validation-for="EmployeeNumber" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
This is how I am getting the employee Data from the database:
public class LookUpData : ILookUpData
{
public readonly EmployeeRecognition.Models.EmployeeRecognitionContext _empContext;
public LookUpData(EmployeeRecognition.Models.EmployeeRecognitionContext empContext)
{
_empContext = empContext;
}
}
when I click on the submit button and dont select anything from employee drop down, I dont get a validation error saying "Employee Name is Required". I know I am sending value 0 to the controller, but how can I display the validation message when the end user does not select anything from the drop down list when 0 is pre sected. This field is required on the database side too. if (ModelState.IsValid) is always coming true. I am sending 0 to the controller, but is their any work around for that?