MVC 6 View Components vs. Partial Views: What is the difference? When should each be used?

asp.netasp.net Core-Mvc

asp.net Problem Overview


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?

asp.net Solutions


Solution 1 - asp.net

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 - asp.net

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 - asp.net

ViewComponents 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAswajithView Question on Stackoverflow
Solution 1 - asp.netJalpesh VadgamaView Answer on Stackoverflow
Solution 2 - asp.netKiranView Answer on Stackoverflow
Solution 3 - asp.netAlexe BarlescuView Answer on Stackoverflow