How to use DisplayTemplates in MVC core 2.0

拥有回忆 提交于 2019-12-12 10:53:30

问题


I used to use DisplayTemplates in MVC5 to get rid off foreach loops from views

If I have a ProductDto and ProductController

I would place a ProductDto.cshtml under

Views/Product/DisplayTemplates/

or

Views/Shared/DisplayTemplates/

to use the template for list of products: I would replace the foreach loops with the following line to list all products by using the template: @Html.DisplayFor(m=>m.Products);

And if I want to use same model (ProductDto) in a different display template for instance let's say ProductDtoPrintView then I would create another template under Views/Product/DisplayTemplates/ with name ProductDtoPrintView.cshtml and pass the templateName as @Html.DisplayFor(m=>m.Products,"ProductDtoPrintView").

But this does not seem to work in MVC Core 2.0

I can only get one template working for each model. And templateName does not seem to have any impact at all.

My testing:

When ProductDto.cshtml is placed under Views/Product/DisplayTemplates/

If I have only one display template for ProductDto model then the templateName really doesn't seem to have any impact. It works with any name or without name.

@Html.DisplayFor(x =>x.Products) -- works @Html.DisplayFor(x =>x.Products,"") -- works @Html.DisplayFor(x =>x.Products,"whatever") -- works

But when I add another display template for the same Model as ProductDtoPrintView.cshtml

Then things get screwed a bit.

@Html.DisplayFor(x =>x.Products) --works

@Html.DisplayFor(x =>x.Products,"") --works

@Html.DisplayFor(x =>x.Products,"") --works

@Html.DisplayFor(x =>x.Product, "ProductDtoPrintView") --doesn't work 500 internal server error.

@Html.DisplayFor(x =>x.Products, "ProductDto") --doesnt work - 500 error

@Html.DisplayFor(x =>x.Products, "DisplayTemplates/ProductDto") --works and returns ProductDto.cshtml template

@Html.DisplayFor(x =>x.Products, "DisplayTemplates/ProductDtoWhatever") --works and returns ProductDto.cshtml template

@Html.DisplayFor(x =>x.Products, "DisplayTemplates/ProductDtoPrintView") --works and returns ProductDto.cshtml template

Basically no way I can get the ProductDtoPrintView working unless if I delete ProductDto.cshtml file.

Anyone experiences the same problem? and how excatly this DisplayTemplates are supposed to work in MVC Core?

来源:https://stackoverflow.com/questions/50582964/how-to-use-displaytemplates-in-mvc-core-2-0

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