I'm new to razor pages and trying to bind the value of two select lists to two model properties. The value is always empty ("") when I try to retrieve it using JavaScript. It works as expected when I give the select element a normal ID but not when I use asp-for="CustomerInfo.ExpMonth". The asp-for binding works for every other input just not the selects.
public class CustomerViewModel
{
public string ExpMonth { get; set; }
public string ExpYear { get; set; }
}
//PageModel
[BindProperty]
public CustomerViewModel CustomerInfo { get; set; }
public void OnGet()
{
ViewData["Months"] = Enumerable.Range(1, 12)
.Select(n => new SelectListItem
{
Value = n.ToString(),
Text = n.ToString()
}).ToList();
ViewData["Years"] = Enumerable.Range(DateTime.Now.Year, 10)
.Select(n => new SelectListItem
{
Value = n.ToString(),
Text = n.ToString()
}).ToList();
}
// html
<form method="post" id="payment-form" onsubmit="submitPaymentForm(); return false;">
<div style="width: 100%; height: 65px;">
<select asp-for="CustomerInfo.ExpMonth" asp-items="@((List<SelectListItem>)ViewData["Months"])">
<option value="" selected disabled="">Expiration Month</option>
</select>
<select asp-for="CustomerInfo.ExpYear" asp-items="@((List<SelectListItem>)ViewData["Years"])">
<option value="" selected disabled="">Expiration Year</option>
</select>
</div>
<input id="submit-button" type="submit" value="Pay Now">
</form>
<script>
function submitPaymentForm() {
var requiredFields = {};
requiredFields["month"] = document.getElementById("CustomerInfo_ExpMonth").value;
requiredFields["year"] = document.getElementById("CustomerInfo_ExpYear").value;
}
</script>
I feel this should be trivial, what am I missing?