Asp.Net mvc 默认情况下 DropDownListFor 中的当前月份

Current month in DropDownListFor by default in Asp.Net mvc

我有几个月 DropDownListFor 并且我想 select 当前月份作为默认月份 我尝试了这两个选项

@{
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)})),

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

您的代码是正确的,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;
}

如果您想要选项标签,请使用

@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;

并按照上述步骤操作。