DropDownListFor中的当前月份,默认情况下为Asp.Net mvc [复制]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我有几个月'DropDownListFor,我想选择当前月份作为默认我尝试了这两个选项

@{
var currentMonth = month.FirstOrDefault(x => x.Id == DateTime.Now.Month).Id;
}

1.

@Html.DropDownListFor(x => x.monthId, new SelectList(month, "Id", "Name", currentMonth  ))

2.

 @Html.DropDownListFor(x => x.monthId, month.Select(x => new SelectListItem
 { Text = x.Name.ToString(), Value = x.Id.ToString(), Selected = (x.Id == currentMonth ?true:false)})),

但都不起作用。我怎样才能实现目标?

c# asp.net asp.net-mvc razor html.dropdownlistfor
2个回答
0
投票

如果你想要一个选项标签,那么使用

@Html.DropDownListFor(x => x.MonthId, new SelectList(month, "Id", "Name", Model.MonthId), "Select Month")

除此以外

@Html.DropDownListFor(x => x.MonthId, new SelectList(month, "Id", "Name", Model.MonthId))

如果这也不起作用,那么尝试在您的模型属性中指定月份ID

Model.MonthId = month.FirstOrDefault(x => x.Id == DateTime.Now.Month).Id;

并按照上述步骤操作。


1
投票

你的代码是正确的,Selected = (x.Id == currentMonth ?true:false)}是没用的,因为你绑定到你的模型的属性monthId,这个属性可能是null。因此,在视图的顶部,在设置currentMonth之后添加以下代码,如下所示:

@{ 
    var currentMonth = month.FirstOrDefault(x => x.Id == DateTime.Now.Month).Id;
    Model.monthId = Model.monthId ?? currentMonth;
}
© www.soinside.com 2019 - 2024. All rights reserved.