Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModel concept still exists in Blazor?

Tags:

blazor

After answering this question about whether the ViewModel is still applicable in MVC Core, I now find myself with a similar question in Blazor.

I'm starting to build my first complex Blazor page with a lot of state to manage. Elements of the page will show/hide and update depending on data entered on other parts of the page.

I've worked with React and Redux in the past and found great value in having a single location for all the state, especially for unit testing purposes.

Accordingly, my plan is to have a view-model that contains not only the data I'm going to persist to the database, but also potentially flags such as ShowSalesOrdersPanel that will then be used in if statements in the razor view.

My question is, should this view-model be a separate class, or is the @functions section of the Blazor razor file effectively the view-model? Should I just use that instead?

like image 398
tomRedox Avatar asked May 14 '19 15:05

tomRedox


2 Answers

After asking this question I came across the Microsoft Blazor team's excellent Blazing Pizzas blazor-workshop worked example.

That example uses a State based approach in a similar way to the approach often adopted in React when using Redux or other Flux based approaches.

This seems like a really good approach that I've found works really well in React. I've written more about what the State based approach consists of in this answer.

like image 190
tomRedox Avatar answered Dec 13 '22 15:12

tomRedox


The @functions Block in Blazor fulfills the same functionality as that of Razor Pages. You can define your objects in the @functions Block, instantiate and use them, etc. The @functions Block is actually what we call "code behind." I guess you know all of that, right ?

Right now no formal best practices are available, as Blazor is still under preliminary development. Best practices require a lengthy experience by the community. You can follow samples produced by Asp.Net team to get some ideas of how to develop in Blazor. As for instance, creating a StateApp class whose responsibility to manage the state of components, etc. Currently one should use his experience and knowledge to style his app. As for instance, Create a folder to contain your Model objects, etc., as for instance, define a Customer model class, and then use it in the @functions Block, and elsewhere. To cut it short: No best practices in Blazor yet.

Hope this helps...

like image 39
enet Avatar answered Dec 13 '22 16:12

enet