I have a form page with DropDownlistFor or select as below:
<select asp-for="LeaveType"
class="form-control" style="max-width:180px"
asp-items="@Html.GetEnumOcp_SelectList<LeaveType>(LeaveType.List, null)">
<option selected="selected" value="">Please select</option>
</select>
I have a viewModel with following property:
public LeaveType LeaveType { get; set; }
this is my enum model:
public class LeaveType(int value, string name) : Enumeration<LeaveType>(value, name)
{
public static readonly LeaveType AnnualLeave = new(1, "AnnualLeave");
public static readonly LeaveType SickLeave = new(2, "SickLeave");
public static readonly LeaveType CompassionateLeave = new(3, "CompassionateLeave");
public static readonly LeaveType UnpaidLeave = new(4, "UnpaidLeave");
}
I have htmlExtension :
public static SelectList GetEnumOcp_SelectList<TEnum>(this IHtmlHelper html,
IReadOnlyCollection<TEnum> isValueUsedForValue, TEnum? selectedValue)
where TEnum : LeaveType
{
var myList = isValueUsedForValue.Select(eachValue => new SelectListItem
{
Text = eachValue.Text,
Value = eachValue.Value.ToString(),
Selected = eachValue.Equals(selectedValue)
}).ToList();
return new SelectList(myList, "Value", "Text");
}
in Index HttpGet action, I have expected LeaveTypes values but When I do post my from (ViewModel) with DropDownList or Select to the controller I have all values except LeaveType property value which is null. Just be aware my enum (LeaveType) is not a struct type that is class.
[HttpGet]
public IActionResult Index()
{
Logger.LogInformation("Leave Index started");
// Populate the form on the first visit
var model = new LeaveViewModel(); // You can initialize with any default data if needed
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(LeaveViewModel model)
{
if (model == null) return NotFound();
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction(nameof(Index));
}
Anyone know why LeaveType property get Null value when I submit the ViewModel to index post action. all fields values have passed successfully except LeaveType. Thanks

Try returning them as a SelectList