【问题标题】:MVC template from folder other than default (EditorTemplates/DisplayTemplates)?来自默认文件夹以外的 MVC 模板(EditorTemplates/DisplayTemplates)?
【发布时间】:2011-10-20 20:22:54
【问题描述】:

您能否将 MVC 指向默认文件夹以外的文件夹(Views/Shared/EditorTemplates & Views/Shared/DisplayTemplates)?我想将它们放在这些子文件夹下的子文件夹中,或者放在共享文件夹之外的其他文件夹中。

例如,如果我在这个文件夹下有一个编辑器模板:

~\Views\Order\ProductModel.cshtml

如何告诉我的 EditorFor 模板使用这个模板名称?

我尝试完全限定它,但这不起作用:

@Html.EditorFor(m => m.ProductModel, @"~\Views\Order\ProductModel.cshtml")

我尝试过使用正斜杠和反斜杠,有/没有.chstml,我能想到的每一种组合。我开始认为这不受支持,但我无法想象为什么不支持。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-templates


    【解决方案1】:

    不,恐怕你不能这样做。

    例如,如果我在这个文件夹下有一个编辑器模板

    这不再是一个编辑器模板。是片面的。如果您想在不同的控制器之间共享编辑器模板,您只需将它们放在 ~/Views/Shared/EditorTemplates 文件夹中即可。

    就子文件夹而言,您可以这样做:

    @Html.EditorFor(x => x.Foo, "Order/ProductModel")
    

    这将呈现~/Views/CurrentController/EditorTemplates/Order/ProductModel.cshtml~/Views/Shared/EditorTemplates/Order/ProductModel.cshtml 编辑器模板。

    【讨论】:

    • 这是有道理的。我不知道您可以在控制器的视图文件夹下拥有 Editor/DisplayTemplate 文件夹。这完成了我正在尝试做的事情。谢谢达林。
    • 第二条路径:~/Views/Shared/EditorTemplates/Order/ProductModel.cshtml 没有为我找到...有什么问题吗?
    • 实际上它找到了,但给了我一个错误:The model item passed into the dictionary is of type 'System.Collections.Generic.List``1[Whatever.Models.ProductModel]', but this dictionary requires a model item of type 'Whatever.Models.ProductModel'.
    • 在你的例子中 Foo 是List<ProductModel>
    • @Dmitry 见这里 - stackoverflow.com/questions/5818351/…。 tldr - 通过显式设置您的 EditorFor 以使用特定的编辑器模板,您是在告诉它在整个枚举中使用该编辑器模板,而不是默认情况下允许对可枚举进行模板化,而依次为每个枚举项使用模板“
    【解决方案2】:

    老问题,但是...为特定控制器添加显示/编辑器模板的正确方法是将其添加到 DisplayTemplatesEditorTemplates 子文件夹中。

    假设在您的示例中,您有 OrderController,您可以简单地将模型的显示模板放入子文件夹中,如下所示:

    ~\Views\Order\DisplayTemplates\ProductModel.cshtml
    

    然后,从您的视图中正常调用显示模板(例如:从`~\Views\Order\Index.cshtml):

    @Html.DisplayFor(m => m.MyProductModelProperty)
    

    【讨论】:

    • 这个答案更好地解决了编辑器/显示模板在共享但包含在某个控制器中没有意义时的问题。这避免了尝试重用有时为了可维护性而不能重用的东西。给这个答案一票。
    【解决方案3】:

    如果你这样做:

    @Html.EditorFor(x => x.Foo, "Order/ProductModel")
    

    它不会将 Foo 解析为一个集合并将您的编辑器模板应用于每个项目。它宁愿假设您的编辑器模板应该应用于整个集合。

    如果您想将编辑器模板单独应用于每个项目,只需将其放在视图文件夹下的 EditorTemplates 文件夹中(因为它具有优先级)并使用默认语法:

    @Html.EditorFor(x => x.Foo)
    

    当然,编辑器模板的名称必须与您收藏中的项目类型相匹配。

    【讨论】:

      猜你喜欢
      • 2013-06-08
      • 1970-01-01
      • 2017-08-10
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多