In our new project we use View Compoments in our existing MVC App for separated and reusable components. Lately Blazor has taken some serious steps forward. We recognized that it's much more convenient using Blazor Components for like asynchronous tasks. For example adding an item to a cart:
View Component (old approach):
In a View Component we need to make an AJAX - POST to add a position and then reload the cart view component via an AJAX - GET request.
Razor component (new approach)
official docs: https://docs.microsoft.com/en-us/aspnet/core/blazor/integrate-components?view=aspnetcore-3.1
In a Razor component we simply call the underlying @code - method to add a position and can invoke an event which rerenders the cart view component. So we can go without JavaScript at all. Below a working example in my MVC app:
ProductList.razor
<div>
@foreach (var c in products)
{
<div class="row">
<div class="col-md-3">
<img src="@c.ImageURL" class="img-fluid p-3" alt="@c.Description ">
</div>
<div class="col-md-9">
<div class="row">
<div class="col-12 d-flex">
<span class="font-weight-bold mr-auto">@c.Title</span>
<span class="ml-auto">@c.Number</span>
</div>
</div>
<button class="btnAddToCart" @onclick="(() => addposition(c.ID))"><i class="fas fa-shopping-cart"></i></button>
</div>
</div>
}
ProductList.razor.cs
Separated the code, but works the same as when I put it in "@Code()" on my razor component (inherits vom ComponentBase)
public partial class ProductList : ComponentBase
{
[Inject] Business.Cart cart { get; set; }
[Inject] Business.Product product { get; set; }
protected List<ListProduct> products = new List<ListProduct>();
protected override async Task OnInitializedAsync()
{
List<ListProduct> temp = await product.GetProductList(new GetProductListRequest { CategoryURL = UrlDesc });
products = temp;
}
protected async Task addposition(int artid)
{
CartAddPositionResponse resp = await cart.AddPosition(new CartAddPositionRequest { ProductID = artid });
cart.CallRequestRefresh();
}
}
Catalog.cshtml (MVC View)
<component type="typeof(ProductList)" render-mode="ServerPrerendered" param-urlDesc="@Model.urlDesc"/>
This leads to the following question:
Are there any reasons to use View Components at all, if I just can use Blazor Components, which provide the advantage of calling asynchronous methods directly and can be reused multiple times anywhere in the project? Are there and disadvantages?