MVC template from folder other than default (EditorTemplates/DisplayTemplates)?

醉酒当歌 提交于 2019-11-28 19:06:54

No, I am afraid you can't do this.

For example, if I have an editor template under this folder

That's no longer an editor template. It's a partial. If you want to share editor templates between different controllers you can simply put them inside the ~/Views/Shared/EditorTemplates folder.

As far as subfolders are concerned then you could do this:

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

which will render the ~/Views/CurrentController/EditorTemplates/Order/ProductModel.cshtml or ~/Views/Shared/EditorTemplates/Order/ProductModel.cshtml editor template.

Old question, but... proper way to add display/editor template for specific controller is to add it in DisplayTemplates or EditorTemplates subfolder.

Assuming that, in your example, you have OrderController, you can simply put display template for your model into sub-folder, like this:

~\Views\Order\DisplayTemplates\ProductModel.cshtml

Then, call display template normally from your view (ex: from `~\Views\Order\Index.cshtml):

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

If you do this:

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

it won't parse Foo as a collection and apply your editor template to each item. It will rather assume that your editor template should be applied to the collection as a whole.

If you want to apply editor template to each item individually, just place it in EditorTemplates folder under your view folder (as it will have precedence) and use the default syntax:

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

Of course, the name of the editor template has to match the type of items in your collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!