Html.DropDownListFor in the Template editor does not set the selected value

I have an Html.DropDownListFor in the Editor Template that dots the given selected value. If I replaced the Template editor with a partial view (copy the HTML in the editor in the Partial View), it will work.

code example

Model:

public class MainItemViewModel
{
    public int MainItemId { get; set; }
    public ItemViewModel ItemViewModel { get; set; }
}

public class ItemViewModel
{
    public int ItemId { get; set; }
    public string Text { get; set; }
    public IEnumerable<SelectListItem> ItemSelectList { get; set; }
}

Controller:

public class DropDownController : Controller
{
    //
    // GET: /DropDown/

    public ActionResult Index()
    {
        var mainItemViewmodel = new MainItemViewModel();
        mainItemViewmodel.MainItemId = 2;
        mainItemViewmodel.ItemViewModel = new ItemViewModel();
        mainItemViewmodel.ItemViewModel.ItemId = 2;
        mainItemViewmodel.ItemViewModel.Text = "bla5";
        List<SelectListItem> someItems =  new List<SelectListItem>(){new SelectListItem(){Value = "1",Text = "Test1"},new SelectListItem(){Value = "2",Text = "Test2"}};
        mainItemViewmodel.ItemViewModel.ItemSelectList = someItems;
        return View(mainItemViewmodel);
    }

    [HttpPost]
    public ActionResult Index(MainItemViewModel mainItemViewModel)
    {
        return RedirectToAction("Index");
    }

}

DropDown \ Index.chtml

@model MainItemViewModel


@using (Html.BeginForm())
{
 <br/>
 @Html.TextBoxFor(model => model.MainItemId)
 <br/>
 @Html.EditorFor(model => model.ItemViewModel)

 <input name="submit" type="submit" value="submit"/>
}

DropDown \ EditorTemplates \ ItemViewModel.chtml

   @model ItemViewModel
   @{
   @Html.DropDownListFor(model => model.ItemId, Model.ItemSelectList, "Select Item");
   <br/>

    @Html.TextBoxFor(model => model.Text);
   }

DropDownListFor (model => model.ItemId, Model.ItemSelectList, "Select Element"); doesn't choose 2.I thought that it’s actually supposed to automatically choose for you

I did the same except , having another view model in another for my entire drop-down list, and it worked just fine.

, , , .

DropDownListFor

DropDownListFor - ""

+5
1

, ItemId ItemViewModel

ViewModel :

public ActionResult Edit()
{
   var viewModel = new MainViewModel
                              {
                                  ItemViewModel = new ItemViewModel{ ItemId = 7 }
                              };
   return View(viewModel);
}

,

0

All Articles