c# - ASP.NET MVC 找不到显示模板部分 View

标签 c# asp.net-mvc asp.net-mvc-5

我不确定我在这里做错了什么。我正在使用的模型的默认显示模板未被使用。

此代码位于我的主操作 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 已就位。

enter image description here

我做错了什么?

最佳答案

与 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/

相关文章:

c# - 如何对同一数组中的随机位置执行多线程操作?

asp.net-mvc - 在 app_code/helper.cshtml 文件中使用 Kendo UI

c# - 配置.cs文件asp.net 5 mvc

asp.net - C# Web API 模型绑定(bind)器提供程序应该如何工作?

authorization - 如何将管理员的更改传播到用户的声明

c# - 如何将 BitmapImage 从内存保存到 WPF C# 中的文件中?

c# - 如何在运行 asp.net 页面时以编程方式设置表格背景?

c# - 有没有一种简单的方法可以找出类抛出的异常类型?

asp.net-mvc - ASP.NET MVC 2 中的 DataAnnotationsModelBinder 问题

asp.net-mvc - 何时使用RedirectToAction以及在哪里使用RedirectToRouteResult?