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?
In an earlier version of MVC, we used to have a partial view for that because we want to display it on multiple pages and that partial view is bind to an action in the controller or you need to pass model with every action where you are showing the cart.In view component, it does not depend on controller or models.
A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.
Partial View can be a parent view and we can use it as a parent view of any partial view. We can simply pass Model to show data in the partial view or we can send the data in the partial view with the help of AJAX call.
You can only return one value from a function so you can't return multiple partials from one action method.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With