Item 30 of 295 Previous | Next

1
Vote

ListBox doesn't select values if used in an editor template

description

When using Html.ListBox() or Html.ListBoxFor() in an editor template, it doesn't select any value according to the model. This happens only for the initial GET request when ModelState is not populated.

I have looked in MVC source codes. I'm not 100% sure, but I think there is a problem in the method System.Web.Mvc.Html.SelecteExtensions.SelectInternal(). During initial request ModelState is empty, so line with GetModelStateValue won't get selected values. At following lines there is a code htmlHelper.ViewData.Eval(name). It should get selected values from the model. But it is called with full field name (with prefix) againt partial model ("Inner.SelectedValues" against InnerModel in the following example). I think there should be used only partial field name ("SelectedValues" in the following example). Obviously this affects DropDownList too.

Example:
public class OuterModel
{
public InnerModel Inner { get; set; }
}

public class InnerModel
{
public IEnumerable<int> SelectedValues { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
public InnerModel() // Constructor
{
Items = // Create some items, there will be items with values 1, 2
SelectedValues = new[] { 1, 2 };
}
}

SomeView.aspx with model OuterModel:
<%: Html.EditorFor(m => m.Inner) %>

EditorTemplates/InnerModel.ascx with model InnerModel:
<%: Html.ListBoxFor(m => m.SelectedValues, Model.Items) %>

No files are attached

comments