Why is DropDownListFor not recognizing the selecte

2019-04-10 16:21发布

问题:

I have the following editor template called 'DropDown.cshtml'. The list part works fine, and the template uses some voodoo I did to get the required SelectList from ViewData. The controller places all select lists in the view model into ViewData, and there is nothing wrong with the list side of things.

@{
    var list = this.GetModelSelectList();
}
@Html.DropDownListFor(m => Model, list)

I use this template on foreign key view model properties like this one:

[Required]
[UIHint("DropDown", "MVC", "SelectListName", "JobLevelSelectList")]
[Display(Name = "Job Level")]
public Guid? JobLevelId { get; set; }

public SelectList JobLevelSelectList { get; set; }

In the controller, JobLevelId has the correct value immediately before executing the view, yet no item it selected in the rendered select element. or rather, the first item in the select list is always selected.

Why does DropDownListFor ignore the property value when used in my editor template and yet work fine when invoked directly?

回答1:

This is unfortunately a known bug in MVC3 (I haven't tried it in MVC 4 Beta to see if it fixed).

The work around that I have used is to manually set the Selected property accordingly in collection that the DropDownListFor is bound to, it is not ideal but it worked.