1

I have Months' DropDownListFor and I want to select current month as default I tried this two options

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

but neither works. How can I achieve my goal?

2 Answers2

1

You code is correct and Selected = (x.Id == currentMonth ?true:false)} is useless because you're binding to the property monthId of your model and this property is probably null. So at the top of your view add the following code after setting the currentMonth like below:

@{ 
    var currentMonth = month.FirstOrDefault(x => x.Id == DateTime.Now.Month).Id;
    Model.monthId = Model.monthId ?? currentMonth;
}
CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
0

If you want with an option label then use

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

otherwise

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

if that's also not work then try to assign month id in your model property

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

and follow the above steps.

Sunil Shrestha
  • 303
  • 1
  • 7