我有几个月' 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)})),
但不起作用。 我怎样才能实现目标?
答案 0 :(得分: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;
}
答案 1 :(得分:0)
如果您想使用选项标签,请使用
df <- as.tibble(rbind(agreement, likelihood))
> as.character(df[1,1:5])
[1] "Strongly Disagree" " Disagree" "Neither" "Agree" "Strongly Agree"
,否则
@Html.DropDownListFor(x => x.MonthId, new SelectList(month, "Id", "Name", Model.MonthId), "Select Month")
如果这也不起作用,那么尝试在模型属性中分配月份ID
@Html.DropDownListFor(x => x.MonthId, new SelectList(month, "Id", "Name", Model.MonthId))
并按照上述步骤操作。