I have a Html.DropDownListFor in an Editor Template which does dot set a selected value. If I replace the editor Template with a partial view(copy paste of HTML in editor template to the Partial View) it works.
sample code
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);
}
The DropDownListFor(model => model.ItemId, Model.ItemSelectList, "Select Item"); does not select 2.I thought it is actually supposed to automatically select for you
I have been doing the same thing except having another view model within another for all my dropdownlist and it has worked fine.
Is there a problem with editor Templates and dropdownlist,I have looked at most answers to this problem and I do not see any conclusive answer that works I have looked at these solutions
Problem binding selected value to DropDownListFor inside Editor Template