ASP.Net Core: ViewComponent vs EditorTemplate/DisplayTemplate vs @inject

.net coreasp.net-core

So I was searching for a good way in ASP.Net Core to create some "controls" that render into a view. So far I found there are 3 options, and I wanted to get some feedback on them.

  1. ViewComponents: These are like mini controllers and use methods like actions to render from a razor page (view). I believe they can have self-contained logic so there's no dependency on any parent view model.

  2. EditorTemplate/DisplayTemplate folders: These exist under "Views/Shared/" and could be pulled into a view by passing a model property to them (using DisplayFor() or EditorFor()).

  3. @inject for ASP.Net Core: Allows injecting a type into a view (I have no idea if a partial view can be associated?).

  4. I'm leaving out the ability to include partial views directly, as it is not my intent for the control system I'm porting over.

  5. Tag Helpers – it's possible to inject the current view context and build controls from these also.

In an older ASP.NET MVC app I had some controls that rendered from the templates (#2). However for .Net Core, I'm contemplating on possibly using ViewComponents instead (which seem more powerful) for rendering associated razor views (the controls basically just wrap razor views). For the moment I'll be experimenting with converting to ViewComponents, but would love some advice on the matter, thanks.

Best Answer

Use ViewComponent if you have some business logic to run. It supports Separation of Concerns (SoC) principle. You can inject parameters to ViewComponent class from view (use razor .cshtml file). ViewComponent views can be found in Views/Shared/Components. It can be strongly-typed. ViewComponent use asynchronous method calls, so users doesn't have to wait for all of the content of an entire page to load. Moreover, ViewComponent can be invoked as Tag Helper: you need to add your ViewCompenent as Tag Helper using @addTagHelpers directive. This feature gives developer editor support in the razor editor template.

Use Editor/Display Template when editing or displaying certain types or classes. For example, you want to specify that Product object must appear with specification table. It preserves DRY principle in your MVC application. It can be used as partial view that is model bound to the object it wants to display.

Related Topic