Using View Models in Blazor
A developer gives a quick tutorial on working with view models in the C# development framework, Blazor, showing some basic code to get you started.
Join the DZone community and get the full member experience.
Join For FreeBeing new to Blazor (and Razor), the first thing that tripped me up was that the view seemed divorced from the rest of the application. In fact, this is actually quite a nice design, as it forces the use of DI.
For example, say you wanted to create a View Model for your view, you could register that ViewModel in the Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MyViewModel, MyViewModel>();
}
Note here that you don't need an interface. If you're only creating an interface for the purpose of this then that abstraction provides no benefit. That isn't to say there may not be a reason for having an interface, but if you have one and this is the only place it's used, you probably should reconsider.
The views in Razor/Blazor (at the time of writing) are *.razor files. In order to resolve the dependency inside the view, you would use the following syntax:
@page "/"
@inject ViewModels.MyViewModel MyViewModel
(Note that @page "/"
is only in this snippet to orientate the code.)
You can call initialization in the view model using something like:
@code {
protected override async Task OnInitAsync()
{
await MyViewModel.Init();
}
}
And, within your HTML, you can reference the view model like this:
<div>@MyViewModel.MyData</div>
Magic. Hopefully more to come on Blazor soon.
Published at DZone with permission of Paul Michaels, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments