6

I have the following code

public class TestModel
{
   public int TestId1 { get; set; }
   public int TestId2 { get; set; }
   public int TestId3 { get; set; }
   public List<TestSubModel> SubMods { get; set; }

   public IEnumerable<SelectListItem> SelectListItems { get; set; }
}

public class TestSubModel
{
   public string ItemId { get; set; }
}

public class HomeController : Controller
{
   public ActionResult Index()
   {
      var m = new TestModel
      {
         TestId1 = 1,
         TestId2 = 2,
         TestId3 = 3,
         SelectListItems = new List<SelectListItem> { 
                         new SelectListItem { Value = "1", Text = "Item 1" },
                         new SelectListItem { Value = "2", Text = "Item 2" },
                         new SelectListItem { Value = "3", Text = "Item 3" }
                      },
         SubMods = new List<TestSubModel> { 
                         new TestSubModel { ItemId = "1" },
                         new TestSubModel { ItemId = "2" },
                         new TestSubModel { ItemId = "3" }
                      }
      };
      return View(m);
   }
}

and the View:

@model MvcApplication2.Controllers.TestModel

@using (Html.BeginForm())
{
   <ul>
      <li>Test1 Value @Model.TestId1 : @Html.DropDownListFor(i => i.TestId1, Model.SelectListItems)</li>
      <li>Test2 Value @Model.TestId2 : @Html.DropDownListFor(i => i.TestId2, Model.SelectListItems)</li>
      <li>Test3 Value @Model.TestId3 : @Html.DropDownListFor(i => i.TestId3, Model.SelectListItems)</li>
      <li></li>
      @for (var index = 0; index < Model.SubMods.Count(); index++)
      {
         <li>SubModel @index: value @Model.SubMods[index].ItemId
                      @Html.DropDownListFor(i => i.SubMods[index].ItemId, Model.SelectListItems)</li>
      }
   </ul>
}

And the output is:

Result

What I expect is Item 1, Item 2 and Item 3 selected twice. Why does Razor not select the correct items in the for loop?

This also doen't work:

@Html.DropDownListFor(i => i.SubMods[index].ItemId, 
                      new SelectList(Model.SelectListItems, "Value", "Text"))

But this does:

@Html.DropDownListFor(i => i.SubMods[index].ItemId, 
                      new SelectList(Model.SelectListItems, "Value", "Text", Model.SubMods[index].ItemId))

I really don't want to create a new selectlist every time. Is this a bug or am I missing something?

I saw this question from 2010 but without an answer.

Community
  • 1
  • 1
John Landheer
  • 3,999
  • 4
  • 29
  • 53
  • 1
    The `DropDownListFor` working differently than the other helpers like `TextBoxFor` and it is currently not supports experssions which has array index (like `i => i.SubMods[index].ItemId`) when looking for the default value. So the only workaround what you already know is to provide a `SelectList` where you explicitly set the selected item. – nemesv Jun 29 '13 at 17:07

0 Answers0