I have the following code in an editor template called DropDown
, which I invoke with a UIHint
.
if (ViewData.ModelMetadata.AdditionalValues.ContainsKey("TemplateControlParameters"))
{
var cparms = (Dictionary<string, object>)ViewData.ModelMetadata.AdditionalValues["TemplateControlParameters"];
var listName = cparms["SelectListName"].ToString();
list = (SelectList)ViewData[listName];
}
The SelectListName control parameter is supposed to point to a SelectList
property of the 'outer' model, i.e. the model that contains the property being edited by this template. However, I can't find a way to reference the containing model instance, only the containing model type. How can I access the instance of the model that this template is being invoked for?
CLOSEST SOLUTION: I have created a derived Controller class that overrides View(string viewName, string masterName, object model)
and injects the view model's select list dictionary (IDictionary<string, SelectList>
) into the view data:
protected override ViewResult View(string viewName, string masterName, object model)
{
var result = base.View(viewName, masterName, model);
if ((model is ViewModelBase) && (!ViewData.ContainsKey(SelectListsViewDataKey)))
{
var vm = (ViewModelBase)model;
result.ViewData.Add(SelectListsViewDataKey, vm.GetSelectLists());
}
return result;
}