WPF MVVM vs Razor Page MVVM - c#

MVVM pattern in WPF has a strong emphasis on completely separating the ViewModel from the UI, and ideally has nothing or very little in the code-behind file. This allows to re-use the ViewModel for different types of interface.
MVVM pattern in Razor Pages has the code-behind as the ViewModel and is tightly coupled with the web logic with OnGet and OnPost methods.
Thus, the carefully-crafted decoupled WPF ViewModel cannot serve as the Web ViewModel (or perhaps can be used from the web page Model?)
Is there something I'm missing, and why is there such a difference between MVVM in WPF (decoupled) and MVVM in Razor Pages (coupled)?
If we were to apply the Razor Pages approach to WPF, then the code-behind would become the ViewModel -- which I've never seen anyone recommend.

To make things clear: WPF introduces a coupling between the view and the view model the same way Razor Pages does. The view model is a data representation layer in order to break the dependency between the view and the model. So the view can be changed without modifying any models. The view model itself is then coupled to the model since it fetches the required data (e.g. from a service or data base).
This behavior is realized in Razor Pages in a unified pattern by having the view models implement the abstract PageModel and by following a convention by providing the appropriate optional action handlers (e.g. OnGet()). Those handlers will be invoked by the framework anytime a HTTP request was issued for the page. You would fetch or manipulate model data based on the request method (e.g. GET, DELETE, POST, PUT, ...) and then present it to the view. The convention describes the naming pattern of those handlers so that the framework can identify them.
So you'll find the same degree of coupling between the layers in WPF MVVM and Razor Pages MVVM. Since the view model in RazorPages encapsulates the context of a specific page the source file naming follows a naming convention ("page name.cshtml.cs") to make the relationship visible in your filesystem. It's not a code-behind file like the partial class file of a view in WPF.

I'm not sure why you insist on using Razor Pages, when there is MVC (Model-View-Controller).
You should use the MVC pattern instead. You get the same razor syntax but decoupled.
Razor Pages were introduced as a form of successor to WebForms (which itself tried to mimic Windows Forms, which isn't about decoupling neither).
If we go a few years back in history, MVVM was to use the full power of WPF's Two-Way Model binding, which acts as a separate layer between the UI and Application layer where one can put presentation logic in (logic tightly coupled to the Presentation, which is an UI concern rather than application layer which is decoupled from the UI).
For that reasons the MVVM's ViewModels also have (additionally to properties for Model Binding), things like Commands and may be Navigation aware (i.e. via Prism's INavigationAware interfaces).
In this context, ViewModels aren't of much value in server-sided web applications, because HTTP by itself, is stateless where ViewModels maintain a state.
Thus the ViewModels in MVC are simply reduced to DTOs (Data Transfer Objects), which has basic validation (through validation attributes). ViewModels in MVC Applications don't have any presentation logic, due to the fact its rendered into HTML and most presentation Logic happens outside via JavaScript (what happens when a button is clicked, how to format a date or currency for a user).
That being said, you don't really need full-fleged ViewModels in an ASP.NET Core application, at least not for the server-sided part. However, if you are using a client-sided technology (Angular, Vue.js, React) you may utilize ViewModels to enhance the functionality and decouple it from the View.
In fact, angular components are pretty much ViewModels and fulfill the same task as ViewModels in MVVM pattern do (one can inject services into it, has 1-way or 2-way bindings, input validation and one puts presentation logic in them).
TL;DR: You don't really need ViewModels as they are defined in MVVM, just DTO-like classes to make consuming them in the (Razor)View Template easier. And don't use Razor Pages for decoupling.

Related

What should go in [Name]View.xaml.cs files?

I am creating a desktop application using WPF & Caliburn MVVM. In my "Views" directory, I have several files that follow this pattern:
ExampleView.xaml <= this is the actual UI design...
ExampleView.xaml.cs <= what goes here?
Then I also have a ViewModel for each view.
Can somebody explain what should go in the ExampleViewModel.cs and what should go in the ExampleView.xaml.cs? It looks like my ViewModels inherit from "Screen", where my ExampleView.xaml.cs inherits from "Window".
Thanks!
That is your "Codebehind" for the view. Many people use the codebehind to interact with their view. However, many people prefer a decoupled approach called MVVM that uses a viewmodel instead. The MVVM architecture is more unit-testing friendly and easier for code reuse.
So in summary, the ExampleView.xaml.cs is used to interact with your controls on the view.
Well, your views can be inherited from Window or UserControl or other WPF classes. In MVVM the view is the user interface and the view model is an abstraction of the view exposing public properties and commands. Instead of the controller of the MVC pattern, or the presenter of the MVP pattern, MVVM has a binder. In the view model, the binder mediates communication between the view and the data binder.
But your view can contains UI-logic that is not depend on data from ViewModel. This logic can be added to [Name]View.xaml.cs files as View's (and inner control's) event handlers, for example OnLoad, OnResize. It calls Code behind.
I just wrote a couple WPF apps using MVVMLight Nuget and all of my [views].aspx.cs only have the auto-generated code. I didn't need to put anything in the views code behind because it goes in my view model. I also converted some web apps and a couple windows 8 store apps to MVVM and almost completely eliminated all code from the views code behind.
The only time I have put something in the views code behind is maybe to instantiate a view model to go along with that view in very isolated situations.
There is much debate out there whether to have zero code to follow MVVM best or having some code in the code behind is okay. Personal preference and based on work load, complexity, timelines, etc.

Should viewmodels contain static functional methods?

If I have a Viewmodel designed to serve a purpose for a view -
Is it a good practice to add bunch of static methods to the viewmodel like
- getting a list of items(viewmodel object) by consuming data from db?
- updating the db using a property in the viewmodel?
I am using .NET MVC and feel like my viewmodels get cluttered with bunch of static functions and update methods.
The main reason behind creating viewmodel for the views was because the views started to contain a lot of functionalities for which info had to be fetched from all over the place. So instead, i decided to create a viewmodel to get the info from one place with one call.
Am I following a good coding pattern here? Or am I shooting in the dark?
Is it a good practice to add bunch of static methods to the viewmodel
No, your viewmodel should simply be a POCO, containing as little (if not zero) business logic. A view models only job is to move data from the controller to the view.
Generally:
The controller should obtain an instance of a model from somewhere
this can be consumed by the view directly or if multiple models needs
combining or extra information (not in a model per se) is required
then a view model can be created.
Ideally the view model should be created outside of the controller
(keeping the controllers job clean), this can be achived simply by
using a factory pattern
If you read the wikipedia page for the MVC pattern. You'll notice it is solely designed for the presentation of data, not business logic:
Model–view–controller (MVC) is a software architectural pattern for
implementing user interfaces.
so really none of the MVC objects (Model, View or controller) should contain business logic. The MVC patterns job is to render data (full stop)
That all said it is common to put simple business logic into the controller. Once sites get more complex, though, this should be avoided, for fear of creating a god object
Am I following a good coding pattern here?
No, it's not a good pattern.
The main reason behind creating viewmodel for the views was because the views started to contain a lot of functionalities for which info had to be fetched from all over the place. So instead, i decided to create a viewmodel to get the info from one place with one call.
Store functionalities or any kind of logic is not the ViewModel's purpose. It should be just a transport mechanism that holds the data transported between the View and the Controller.
Consider move your "funcionalities" to Application, Service or another layer that makes sense for your application's architecture.

Is MVC specific to Web application?

I might sound very naive here.
Does MVC applies only for Web application? I have worked on MVVM for quite some days and I see people telling MVVM with WPF is a windows version of MVC.
What would be the alternate solution for MVC or MVVM as of now? Isn't any design patterns better than this discovered yet?
I am very specific to .NET here.
No. Mvc is not specific to web applications or .net.
All the mvx patterns have in common the view and the model. The view is concerned with the display of the data, the model delivers the data.
In mvc the data is pulled out of the model by the controller who puts it in the view. The user interactions where delegated from the view to the controller who acts on the model. View and Model does not now of each other.
With new technologies like data binding mvc becomes bulky. Mvp was introduced. It allows for the view to use data binding directly to the model, bypassing the controller who is now called presenter. The presenter orchestrates view and model but has fewer responsibilities.
Later mvp was replaced with mvvm. Here model and view are again completely separated and do not know each other. The Viewmodel is a model that is designed specific to the views needs. It also handles the responsibilities of the controller.
In my opinion the asp.mvc is not truly mvc. You hand out either objects of the model, or special desinged viewmodels to the razor views, so its either more mvp or mvvm with adding a controller to manage the other parts.

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

If we search Google using the phrase "differences between MVC, MVP & MVVM design pattern" then we may get a few URL's which discuss the difference between MVC MVP & MVVM design pattern theoretically like:
MVP
Use in situations where binding via a "dataContext" is not possible.
Windows Forms is a perfect example of this. In order to separate the view from the model, a presenter is needed. Since the view cannot directly bind to the presenter, information must be passed to the view via an interface (IView).
MVVM
Use in situations where binding via a "dataContext" is possible. Why? The various IView interfaces for each view are removed which means less code to maintain.
Some examples where MVVM is possible to include WPF and javascript projects using Knockout.
MVC
Use in situations where the connection between the view and the rest of the program is not always available (and you can’t effectively employ MVVM or MVP).
This clearly describes the situation where a web API is separated from the data sent to the client browsers. Microsoft’s ASP.NET MVC is a great tool for managing such situations and provides a very clear MVC framework
But I have not found a single article which discusses the difference theoretically along with sample code.
It would be really nice if I get an article that discusses the difference between these 3 design patterns (MVC, MVP & MVVM) along with code.
I'd like to get my hands on the source code of 3 similar CRUD apps that have been implemented by these three design patterns (MVC, MVP & MVVM). So that I can go through the code and understand how one should write code for these three design pattern (MVC, MVP & MVVM).
So if any such article exists which discusses how code would look different for these 3 design patterns (MVC, MVP & MVVM) then please redirect me to that article.
Some basic differences can be written in short:
MVC:
Traditional MVC is where there is a
Model: Acts as the model for data
View : Deals with the view to the user which can be the UI
Controller: Controls the interaction between Model and View, where view calls the controller to update model. View can call multiple controllers if needed.
MVP:
Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.
MVVM
The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM.
Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.
MVC, MVP, MVVM
MVC (old one)
MVP (more modular because of its low-coupling. Presenter is a mediator between the View and Model)
MVVM (You already have two-way binding between VM and UI component, so it is more automated than MVP)
Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx
Let's First look at MVC
The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.
There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.
There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.
The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.
MVP – Model View Presenter
Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:
The input begins with the View, not the Presenter.
There is a one-to-one mapping between the View and the associated Presenter.
The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.
The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.
MVVM – Model View View Model
So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:
The input begins with the View, not the View Model.
While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.
MVP:
Advantages:
Presenter will be present in between Model and view.Presenter will fetch data from Model and will do manipulations for data as view wants and give it to view and view is responsible only for rendering.
Disadvantages:
1)We can't use presenter for multiple modules because data is being modified in presenter as desired by one view class.
3)Breaking Clean architecture because data flow should be only outwards but here data is coming back from presenter to View.
MVC:
Advanatages:
Here we have Controller in between view and model.Here data request will be done from controller to view but data will be sent back to view in form of interface but not with controller.So,here controller won't get bloated up because of many transactions.
Disadvantagaes:
Data Manipulation should be done by View as it wants and this will be extra work on UI thread which may effect UI rendering if data processing is more.
MVVM:
After announcing Architectural components,we got access to ViewModel which provided us biggest advantage i.e it's lifecycle aware.So,it won't notify data if view is not available.It is a clean architecture because flow is only in forward mode and data will be notified automatically by LiveData. So,it is Android's recommended architecture.
Even MVVM has a disadvantage. Since it is a lifecycle aware some concepts like alarm or reminder should come outside app.So,in this scenario we can't use MVVM.
The image below is from the article written by Erwin van der Valk:
The article explains the differences and gives some code examples in C#
MVC vs MVP vs MVVM
MVC - Model View Controller
View(.xml, .storyboard) - Controller(Activity, Controller) - Model(Others)
View - rendering UI
Controller is bound with View
MVP - Model View Presenter
View(.xml, .storyboard, Activity, Controller) - Presenter(plain Class) - Model(Others)
MVVM - View Model ModelView
View(.xml with data, view.swift) - ModelView(ViewModel, ObservableObject) - Model(Others)
Android DataBinding, SwiftUI
MVVM uses data binding or two way data binding to connect View and ModelView based on Observation
Sometimes in UI world(iOS, Android) you can find additional object(Router, Navigator, Coordinator) which is responsible for navigation and setting dependencies

WPF: MVP vs MVVM

What is the difference between MVP VS MVVM? Why we are using MVP even though we have three layers: business, data access and presentation? Is there any specific reason to divide the Presentation layer into MVP?
MVP and MVVM are both derivatives of MVC. MVC is a pattern that separates the user presentation and interaction from the internal representation.
This requires three layers, since tying the user interaction/presentation directly to the internal representation will cause both to bend to conform to each other. In your application, you described these layers as the Presentation, the Business layer, and the Data Access layer. With only those very loose descriptions, you could potentially be describing any of the MVC derivatives, or the original MVC pattern itself.
The key differences between each of the derivatives are the dependencies each layer takes on the other layers, and how tightly they are bound to each other. This article has some details on the differences, though of course it shouldn't be considered authoritative:
http://nirajrules.wordpress.com/2009/07/18/mvc-vs-mvp-vs-mvvm/
"... MVVM is attractive for platforms which support bi-directional binding with less effort. Also a minor tradeoff is ViewModel unlike Presenter can stand on its own (Presenter normally requires a View’s interface)."
We use at our company projects of WPF desktop application MVP instead of the built in MVVM for the main reason that in MVP the presenter is the main entry point that knows everything and no one knows about the presenter.
For each View the presenter which have one responsibility which is taking interactions from the IView interfaces by subscribing to events that the View triggers.
The presenter updates the View by a properties that encapsulates the internal View controls like TextBox with string properity and GridView with any Collection property. The constructor of the MainPresenter class will look something like this MainPresenter(IMainView, IEmployeeStore, IOtherDependency,..)
The Constructor of MainView class will look like this MainView(IPartialViewIfExists,..) that means the view does not know anything about the Presenter or anything else outside the View layer (which is the opposite of MVVM that enforces the MainView to directly couple the MainViewModel to automate the
two way databinding).
That clean loosely coupling architecture which the MVP provides is really powerful and flexible which enables the ability for the following:
Your application can replace the GUI with anytime without changing anything in the presenter, you can also change the GUI technology to something else like WinForms or something.
You can separate your GUIs in a separate project that doesn't require any dependencies of your main application like the presenters and dataAccesses
Your View can be used for any other application witch is useful for general GUIs.
You can unit test the views, the presenters and the data access classes easily.
The ViewModel in MVVM doesn't know about the View but I don't think that is helpful since it is responsible for the View. The View shouldn't know about the presenter which handles business logic and that's what exactly the MVP provides (or the way that we implement MVP).
That doesn't mean that MVVM is bad. MVVM is a good architecture and faster to code and easier to start with since it is already implemented in WPF and Xamarin but as I explained we prefer MVP for listed reasons.
In general MVP is cleaner and more scalable but requires more knowledge and coding experience and have to be implemented manually. MVVM is already there, it is easy to use and lets you implement faster but provides coupling and has some limitations. They all have their pros and cons and it depends on your need.

Categories