Reputation: 3279
I have Model, which has following fields:
public List<SelectListItem> Months
{
get
{
return new List<SelectListItem>
{
new SelectListItem {Text = "111", Value = "1"},
new SelectListItem {Text = "222", Value = "2"}
};
}
}
public List<TestModel> ServiceTest { get; set; }
Where TestModel
has one field:
public string Month { get; set; }
Model in view has ServiceTest = new List<ServiceTest> {new ServiceTest {Month = "2"}};
Now, question. Why this
@Html.DropDownListFor(m => m.ServiceTest[0].Month, Model.Months)
doesn't select second value. But this
@Html.DropDownListFor(m => m.ServiceTest[0].Month, new SelectList(Model.Months, "Value", "Text", Model.ServiceTest[0].Month))
work correct. I really don't understand why first expression doesn't work correctly.
Upvotes: 2
Views: 120
Reputation: 2709
In order for the first statement to work, you need to provide the List by which it is bound.
Create a property in your class:
public string[] SelectedMonths { get; set; }
Then use:
@Html.DropDownListFor(m => m.SelectedMonths, new SelectList(Model.Monthes, "Value", "Text", Model.SelectedMonths))
Upvotes: 0
Reputation: 1038720
The reason for this is because the DropDownListFor helper supports only simple expressions when binding the default value. Things like x => x.SomeProp
. In the first example you are using a complex lambda expression (Child property indexer access and yet another child property).
Your second approach is the correct way to solve this limitation of the helper.
Upvotes: 2