MVC 6 View Components vs. Partial Views: What is the difference? When should each be used? [closed]
MVC 6 Introduced View components and said it is much stronger and flexible than partial views. Are view components meant to replace partial views? What is the difference and what kinds of situations call for each implementation?
Solution 1:
According to this link- https://docs.asp.net/en/latest/mvc/views/view-components
New to ASP.NET MVC 6, view components (VCs) are similar to partial views, but they are much more powerful. VCs include the same separation-of-concerns and testability benefits found between a controller and view. You can think of a VC as a mini-controller—it’s responsible for rendering a chunk rather than a whole response.
So it just a enhancement of partial view and another difference is when you use partial view you still have dependency on controller while in View Component you don't need a controller. So there is a separation of concern.
There is a detail post for ASP.NET View Components. http://www.tugberkugurlu.com/archive/exciting-things-about-asp-net-vnext-series-mvc-view-components
Solution 2:
An example where you might want to use a ViewComponent
as opposed to a PartialView
:
You need to write a bunch of business logic where for example you might need to contact a 3rd party web service and get the data and do something with it and then display this information.
For the above scenario, sure you could write C# code in the partial view itself, but its ugly and also you want the code to be testable. So this is where a view component can be useful, i.e you can write all your business logic within a view component and return a view (this is of type ViewViewComponentResult
).
View components are NOT the same as child actions.
Solution 3:
ViewComponent
s are also used when you need a partial view, that requires a model to be called in _Layout. To avoid writing C# code to create the model in the Layout, it's best to use a ViewComponent
that can make use of the Services configured for the application, same as controllers, through dependency injection.