我想写一个HTML助手方法。在我的helper方法中,我想知道主模型的类型(如果有的话)。为了实现这一点,我使用了htmlHelper.ViewData.ModelMetadata.ContainerType,但是当我的助手在模板视图或者可能是其模型是集合的项的分部视图中被调用时,我找不到任何方法来做到这一点。在本例中,htmlHelper.ViewData.ModelMetadata.ContainerType返回null。
示例模型:
public class MyItemCollection
{
public List<MyItemContainer> Collection { get; set; }
}示例EditorTemplate:
@model Test.MyItemContainer
@Html.MyHelper(m=>m.Item)示例视图:
@model Test.MyItemCollection
@for(int i = 0; i < Model.Collection.Count; i++)
{
@Html.EditorFor(m=>m.Collection[i])
}示例操作:
public ActionResult Index()
{
var m = new MyItemCollection();
//Fetching items from Business Logic
m.Collection = FetchItems();
return View(m);
}发布于 2015-05-31 02:14:15
我认为您应该为MyItemCollection创建一个空的构造函数,然后初始化Collection属性。
在该元素没有被另一个过程初始化的情况下,它将导致NULL,这反过来可能导致您正在经历的与反射相关的问题(即:查找ViewData.ModelMetadata.ContainerType)
我说,你自己初始化这个属性。见下文
public class MyItemCollection
{
// added a constructor, so we could initialize Collection.
public MyItemCollection()
{
this.Collecion = new List<MyItemContainer>();
}
public List<MyItemContainer> Collection { get; set; }
}https://stackoverflow.com/questions/30483933
复制相似问题