【发布时间】:2016-11-14 16:37:12
【问题描述】:
我被困在“如何将下拉菜单中的值设置为模型中设置的值。
我正在添加我到目前为止所拥有的以及我尝试过的。
所以,我有一个 PaymentFormMV 模型,其中还有另一个模型 PaymentCCMV
public class PaymentFormMV
{
public PaymentCCMV CreditDetails { get; set; }
public string ModelPropertyPrefixName
{
get
{
return this.ModelPropertyPrefix.Replace("_", ".");
}
}
}
public class PaymentCCMV
{
[Display(Name = "Expiration Date")]
public int ExpirationMonth { get; set; }
}
cshtml 文件从 PaymentFormMV 获取数据
<div class="form-group">
@Html.LabelFor(model => model.CreditDetails.ExpirationMonth, htmlAttributes: new { @class = "control-label col-md-2 required" })
<div class="col-md-10">
@Html.DropDownList(Model.ModelPropertyPrefixName + "CreditDetails.ExpirationMonth", Helpers.PossibleMonths,
new { id = Model.ModelPropertyPrefix + "CreditDetails_ExpirationMonth", @class = "form-control", style = "width:70px;" })
</div>
</div>
Helpers.PossibleMonths:显示所有月份
public static ICollection<SelectListItem> PossibleMonths
{
get
{
return new List<SelectListItem>()
{
new SelectListItem() { Text = "1 - Jan", Value = "1" },
new SelectListItem() { Text = "2 - Feb", Value = "2" },
new SelectListItem() { Text = "3 - Mar", Value = "3" },
new SelectListItem() { Text = "4 - Apr", Value = "4" },
new SelectListItem() { Text = "5 - May", Value = "5" },
new SelectListItem() { Text = "6 - Jun", Value = "6" },
new SelectListItem() { Text = "7 - Jul", Value = "7" },
new SelectListItem() { Text = "8 - Aug", Value = "8" },
new SelectListItem() { Text = "9 - Sep", Value = "9" },
new SelectListItem() { Text = "10 - Oct", Value = "10" },
new SelectListItem() { Text = "11 - Nov", Value = "11" },
new SelectListItem() { Text = "12 - Dec", Value = "12" },
};
}
}
积分:
我得到整数值 model.CreditDetails.ExpirationMonth = 2(根据 DB)
但我不知道如何将其设置为下拉菜单。因此,当屏幕加载时,我希望该值与下拉列表相关联。请指导我。所以,如果值为 2,我应该在帮助方法中提到的下拉 UI 中得到类似 2 - Feb 的内容。我是初学者,所以我可能没有遵循最佳实践,所以请耐心等待。
生成的 HTML:
【问题讨论】:
-
一种方法是使用 HTML.DropDownListFor。然后,如果需要,您可以将模型和默认值作为 SelectList 和 htmlAttributes 提供。
-
非常感谢您的回复。你能详细说明一下吗?
-
将您的代码更改为
@Html.DropDownListFor(m => m.CreditDetails.ExpirationMonth, Helpers.PossibleMonths, new { @class = "form-control", style = "width:70px;" })。如果ExpirationMonth的值是3,那么"Mar"将被选中。 -
附带说明,您的助手可以简化为
return Enumerable.Range(1, 12).Select(x => new SelectListItem{ Value = x.ToString(), Text = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x)); -
@StephenMuecke:非常感谢您的指导。
标签: c# asp.net asp.net-mvc razor asp.net-mvc-5