VOOZH about

URL: https://dzone.com/articles/using-view-models-in-blazor

⇱ Using View Models in Blazor


Related

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.

By Jul. 10, 19 · Tutorial
Likes
Comment
Save
9.9K Views

Join the DZone community and get the full member experience.

Join For Free

Being 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.

Blazor View model

Published at DZone with permission of Paul Michaels. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Build Full-Stack Web App With Firebase, Angular 15, React.js, Vue.js, and Blazor [Video]
  • The Buzz Around Blazor WebAssembly
  • Architectural View Model for Integration Projects

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: