4

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?

ProfK
  • 49,207
  • 121
  • 399
  • 775
  • see http://stackoverflow.com/questions/10039006/mvc-dropdownlist-selectedvalue-not-displaying-correctly – RickAndMSFT Apr 15 '12 at 16:25
  • @RickAndMSFT, I don't see anything in that question or its answers that really applies here. The accepted answer is that the model property in the lambda of `DropDownListFor` overwrites the select list's *selected id*. That doesn't help me with my problem of the 'lambda value' being ignored only in my editor template, not in my raw DDL's. – ProfK Apr 15 '12 at 20:59
  • 1
    I wouldn't be surprised if `ExpressionHelper.GetExpressionText()` (which is what the helpers use to find property names) doesn't work with `m => Model`. – bhamlin Apr 15 '12 at 23:23
  • There is a fix here: https://github.com/davemorgantexas/SelectExtensionFix/blob/master/SelectExtensionFix.cs and how to use it here: http://stackoverflow.com/a/17474222/1751773 – DaveMorganTexas Jul 04 '13 at 15:51

1 Answers1

3

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.

Philip Fourie
  • 111,587
  • 10
  • 63
  • 83