【发布时间】:2020-11-28 15:47:05
【问题描述】:
我是 razor 页面的新手,并试图将两个选择列表的值绑定到两个模型属性。当我尝试使用 JavaScript 检索它时,该值始终为空 ("")。当我给选择元素一个正常的 ID 时,它按预期工作,但在我使用 asp-for="CustomerInfo.ExpMonth" 时却没有。 asp-for 绑定适用于所有其他输入,但不适用于选择。
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>
我觉得这应该是微不足道的,我错过了什么?
【问题讨论】:
标签: javascript asp.net-core .net-core razor-pages selectlistitem