View components
ASP.NET Core view components are similar to partial views but more powerful. You can use view components to render custom logic where you access third-party data sources.
Typically, view components don't use ASP.NET Core model binding, and they only access data on demand. However, the ASP.NET Core SDK provides a service and base component to enable binding a model to the data that Experience Edge returns.
A view component consists of three files:
-
The Razor view
-
The view model class
-
The view component class
Build a view component
To build a view component:
-
Bind a model in your view component in one of two ways:
-
Inherit from
Sitecore.AspNetCore.SDK.RenderingEngine.Mvc, BindingViewComponent
, then invokeBindView
. -
Inject
Sitecore.AspNetCore.SDK.RenderingEngine.Binding.IViewModelBinder
, then invoke an overload ofBind
.
-
-
Map the Experience Edge response to the view component with the
AddViewComponent()
extension method.
Example
Here's an example view component. Note the following:
-
AddViewComponent("Styleguide-Layout", "StyleguideLayout")
maps theStyleguide-Layout
response component to theStyleguideLayoutViewComponent
view component. -
AddViewComponent(name => name.StartsWith("sc"), "OtherViewComponent")
maps all response components prefixed withsc
to theOtherViewComponent
view component.
public void ConfigureServices(IServiceCollection services)
{
var renderingEngineBuilder = services.AddSitecoreRenderingEngine(options =>
options
.AddViewComponent("Styleguide-Layout", "StyleguideLayout")
.AddViewComponent(name => name.StartsWith("sc"), "Other")
);
}