如何访问在剃刀编辑模板包含模型实例? [英] How can I access the containing model instance in a Razor editor template?

查看:95
本文介绍了如何访问在剃刀编辑模板包含模型实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在名为下拉编辑模板,我调用以下code一 UIHint

 如果(ViewData.ModelMetadata.AdditionalValues​​.ContainsKey(TemplateControlParameters))
{
    VAR cparms =(词典<字符串对象>)ViewData.ModelMetadata.AdditionalValues​​ [TemplateControlParameters];
    。VAR LISTNAME = cparms [SelectListName]的ToString();
    名单=(的SelectList)计算机[LISTNAME]
}

SelectListName 的控制参数应该指向外模式的的SelectList 属性,即包含物业作为模型此模板编辑。但是,我无法找到一个方法来引用包含模型实例,仅包含模型类型。我怎样才能访问该模板被调用为模型的实例?

最接近的解决方案:我创建了覆盖视图(字符串的viewName,串masterName,对象模型)并注入该视图派生Controller类模型的选择列表字典(的IDictionary<字符串的SelectList> )到视图中的数据:

 保护覆盖的ViewResult视图(字符串的viewName,串masterName,对象模型)
{
    VAR的结果= base.View(的viewName,masterName,模型);
    如果((型号为ViewModelBase)及&放大器;!(ViewData.ContainsKey(SelectListsViewDataKey)))
    {
        VAR VM =(ViewModelBase)模型;
        result.ViewData.Add(SelectListsViewDataKey,vm.GetSelectLists());
    }
    返回结果;
}


解决方案

您可以得到母公司的元数据,但我不认为你可以得到父模型实例:

  @ {
    VAR ParentType的= ViewData.ModelMetadata.ContainerType;
    VAR元= ModelMetadataProviders.Current.GetMetadataForType(NULL,ParentType的);
}

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;
}

解决方案

You could get the parent metadata but I don't think that you can get the parent model instance:

@{
    var parentType = ViewData.ModelMetadata.ContainerType;
    var metadata = ModelMetadataProviders.Current.GetMetadataForType(null, parentType);
}

这篇关于如何访问在剃刀编辑模板包含模型实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆