我不确定我在这里做错了什么。我正在使用的模型的默认显示模板未被使用。
此代码位于我的主操作 View 中:
@if (Model.EmbeddedMediaModels != null)
{
foreach (var mediaItem in Model.EmbeddedMediaModels)
{
BitmapFigureModel bitmap = mediaItem as BitmapFigureModel;
if (bitmap != null)
{
var mm = ModelMetadata.FromLambdaExpression(p => bitmap, this.ViewData);
var modelTypeName = mm.ModelType.Name; // = "BitmapFigureModel"
// Neither resolve the template.
// Html.DisplayFor(m => bitmap);
Html.DisplayFor(m => bitmap, modelTypeName);
}
}
}
Model.EmbeddedMediaModels
属性是 EmbeddedMediaModel
基本类型的集合,目前它只包含一个对象,即派生自的 BitmapFigureModel
嵌入式媒体模型
。
人们很容易认为这是令人困惑的事情,但检索到的 ModelMetadata
实例完全能够看到正确的 BitmapFigureModel
模型类型。
此外,即使我在对 DisplayFor
的调用中指定模型类型名称,它仍然不起作用。
这里证明正确命名的显示模板部分 View 已就位。
我做错了什么?
最佳答案
与 Brad Wilson(ASP.NET 团队)的建议相反:
The expression-based versions are primarily used for pulling values from the model (they are parametrized by the current model, as shown in the example above). They can also be used for pulling values from some source other than the model or ViewData (for example, with an expression like “model => someOtherValue” which ignores the model entirely). This makes them useful in loops.
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
实际上似乎不可能“完全忽略模型”。在我的问题下的评论中,DaveParsons 建议通过仅新建一个模型实例并将其传递到 DisplayFor
进行实验,这会导致错误:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
所以看来我应该停止自作聪明,而按照 Ehsan Sajjad 的建议使用 Html.Partial
。
关于c# - ASP.NET MVC 找不到显示模板部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23272385/