I would like to create an partial which holds a select for a previously configured list.
in the controller I'm able to create the SelectList
and add it to ViewBag
.
However ViewBag
defined on controller are not propagated to the Partial. Partials have its own ViewBag
for instance this POCO item class:
class MyItem{
[Key]
public int id {get;set;}
public int Forign_element_id {get;set;}
public string PropB {get;set;}
}
And its Partial like this:
@model MyItem
@Html.HiddenFor(model => model.id)
@Html.LabelFor(model => model.PropA)
@Html.DropDownListFor(model => model.Forign_element_id, (SelectList)ViewBag.MySelectList)
//Error! ViewBag are not propageted to the EditorTemplate
@Html.LabelFor(model => model.PropB)
@Html.EditorFor(model => model.PropB)
Important. Each item in the list has a Forign_element_id value. This values must be selected in select box at rendering.
Try this in your editor template: Instead of (Dictionary) cast it to your type; in my case, I was passing Dictionary from the calling layer; so I have used it as new SelectList(list, "Key", "Value"), change accordingly
Name of Editor Template - DropdownList
@{
var defaultText = (string)ViewData["DefaultText"];
//var list = (Dictionary<string, string>) ViewData["List"]; -- my List was Dictionary
var list = (List<YourType>) ViewData["List"];
}
@Html.DropDownListFor(model => model,
new SelectList(list, "Key", "Value"),
defaultText,
new { @class = "form- control", style="height: auto;width:90%" })
EDIT - adding calling code
@Html.EditorFor(model => model.YourModel, "DropdownList", new { List = ViewBag.YourList, DefaultText = "Select one item"})
where "DropdownList" is editor template name