View components encapsulate reusable pieces of logic and views. They are defined by:
Since they contain logic, they are more flexible than partial views while still promoting a good separation of concerns.
A simple custom view component is defined as:
public class MyCustomViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string param1, int param2)
{
//some business logic
//renders ~/Views/Shared/Components/MyCustom/Default.cshtml
return View(new MyCustomModel{ ... });
}
}
@*View file located in ~/Views/Shared/Components/MyCustom/Default.cshtml*@
@model WebApplication1.Models.MyCustomModel
<p>Hello @Model.UserName!</p>
They can be invoked from any view (or even a controller by returning a ViewComponentResult
)
@await Component.InvokeAsync("MyCustom", new {param1 = "foo", param2 = 42})