As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
The way it was explained was through the use of events and the publish/subscribe model. Basically, the model would just be the data and it would have no knowledge of the view/GUI/UI. The model is typically just an abstract object that operates on its data and can perform operations and whatnot.
The view is a different class that responds to changes in the model and usually displays this data to the user. Previously, I did not know how this could occur without coupling between the view and model but having it explained with events clears that confusion up a lot. Does this mean that the model contains public events that itself raises when something interesting happens? For example, if we were programming a game of Chess, when a piece was moved, the model would raise the event of PieceMoved with the necessary information (which piece, moved from where to where, etc.) and the view could subscribe to such an event and then show an animation of the piece moving from its old square to its new square.
The part that still confuses me is the exact nature of the controller. I'm having trouble understanding how it supplies the model and view with new information. I imagine the controller contains references to the model and view. Keeping with the Chess example, would the controller just respond to user input (for example to move a piece) and then just suggest to the model what piece wants to move to where? Then the model takes this information, sees if it's a legitimate move, and if so, update the model accordingly, raise the PieceMoved event, to which the view reacts and updates the graphical realm accordingly?
Lastly, how does the controller find out which piece is trying to be moved? It seems like that type of thing is heavily tied to the view (let's say moving involved first clicking the piece you wish to move and then the destination square). I imagine the controller would respond to a mouse click and sends those coordinates to the model but how would the model know how to translate those coordinates to find which piece was selected? Isn't that heavily tied to the view? It seems like the view would have to perform some logic processing instead of simply responding to the model and controller but then it wouldn't be a proper view anymore (instead a view/model mix).
The bad things about the MVC pattern are:
Everyone has her/his own version
It is a bit abstract to be grasped at first
The good things:
It is actually pretty simple
It is a fantastic way of dividing up most applications
To answer your question though:
The model
This is a easy one. The model should know only about itself. It is the board, the pieces and the rules of the game. You know you are building your model right if you could reuse it either in a desktop application or a web one.
The view
This isn't complex either. It is the visual part, and the one that deals with the user input. The most important concept to understand the role of views in the MVC pattern is that they must provide a way to make calls to the puclic interface of your system. In the chess game, it is the one that has to draw the elements and detect what the user is doing with the mouse/keyboard. When the user does something it is the view the responsible of calling the system: eg. "User1 wants to move piece from X to Y" (Important: most of the time you don't want the view to trigger a call like User1 clicked in coordinates x, y. Pixels are the realm of the view. The system has to receive orders that are independent of how they are graphically represented).
The controller
You're right, this one isn't that straightfoward. The controller is the one that has to process calls to the public interface to the system. In your example it will receive a call 'User1 moves from X to Y' and call a method in the appropiate object of the model (very likely the board in this case). Thus, the controller totally knows about the objects in the model. However it can also contain the code that is necessary in the application but that doesn't belong to the domain of your model. You have to check if the user has permission to access the system? You have to log that call into a file? Well, most of the time that kind of things go into the controller.
However, that's just my own version of MVC (I, like everyone else, also have my own too... :)
MVC is a pretty generic concept. There are tons of different ways that it has been implemented, and most of them have compromises of one sort or another.
The problem I see is that you are trying to take an esoteric concept and apply concrete implementation details to it. That's hard to do unless you have a very specific implementation in mind (asp.net MVC, fubuMVC, spring MVC, smalltalk MVC, whatever) and each one accomplishes things like notifications and event handling in a different manner.
If you're just talking about the MVC concept, then you have to deal with the MVC concepts in a generic way. I know it may be easier to understand if you have a concrete implementation, but then you go down the path of understanding the pattern (MVC) based on the understanding of the implementation, which can skew your understanding of the pattern itself.
So when you read about messages or events, you have to just think "some mechanism that is implementation defined". It could be a callback, or it could be a C# event, or it could be a Windows message, or it could be using the force ;)
EDIT:
Regarding your update, I will repeat. You can't answer implementation specific details about a generic concept. You would have to define a specific implementation for someone to be able to tell you how those implementation details are accomplished.
There's a lot of answers to this question, mainly because there are so many different MVC frameworks. Have a look at http://martinfowler.com/eaaDev/uiArchs.html for some examples. I can also give an MVVM perspective mainly since this is what I've been working on these days so this is how I'm thinking.
The Model layer is basically your data and your business logic. You might be talking to a database or a webservice here. If you end up writing a system, that is more than a just a GUI, this is your reusable code.
The ViewModel then sits on top the Model, and basically presents (ahem) the data as properties. It uses an INotifyPropertyChanged interface to tell the UI when data changes. If you have data that you are using to build something up before pushing it to the model layer, it lives here. You will normally expose the actions that you can perform in the UI as ICommnands.
The View layer is the least coupled, because it just uses binding to connect to the ViewModel. Things to visualise are properties that are bound with optional IValueConverters used to change its form, e.g.
Visibilty="{Binding IsVisible, Converter={StaticResource booleanToVisibiltyConverter}}"
Action UI elements are bound to the Commands on the ViewModel to kick off the ViewModel actions.
Command="{Binding DoSomething}"
So if you have a view (the chess board) and a controller for the chess board, the controller would house the events for it. When you move a piece it raises the PieceMoved event which should pass information to this event such as current position, and desired position.
For a very simple application you may not grasp the concept of models. One might have a billing model that could be reused on multiple views (such as a detail and create view). You wouldn't want to duplicate this code every time you needed it, so in your controller each event would reach out to the billing model that needed it. By creating a model you are encapsulating your code.
Related
I am having a hard time understanding how MVVM is used in case of more complex applications. All the examples I can find are extremely basic Apps.
Let's say I have a "Package Delivery" application. To perform a delivery I have to do 3 steps:
Scan the package
Enter any damages or problems with the package
Let the recipient sign on the device
All this information gets validated on the device and then sent to the backend.
In MVC I would implement this like this:
The DeliveryController handles all of the logic. This includes navigation between pages, fetching of API data and validating all of the data once it is all collected.
The controller acts as the "Connection" between the Views and collects all the information and brings it together.
But how would this be done in MVVM? Where would all the data be brought together? Most implementations of MVVM I can find do something like this:
In this, the data entered in each View would have to be passed to the next ViewModel until the end of the chain is reached. At that point the SignatureViewModel would do the validation and make the API call. That seems very weird and like it would get very confusing, since data would just be "passed through" multiple ViewModels just to have it at the end of the chain.
Another option I see would be that each ViewModel handles it's own data:
Here for instance the DamagesViewModel would validate and send the data it's own View handles. The big issue with this is that data does not get sent as a whole. Also there can not be any validation of the entire data before it is sent.
My last idea would look like this:
This adds a DeliveryViewModel that essentials acts like the DeliveryController does in MVC. It would handle which ViewModel to navigate to next, handle what API calls to make and validate all the data once it is entered.
To me (as someone who has mostly used MVC) this last options seems most sensible. But I also feel like it might miss the point of MVVM.
How is this usually done in MVVM? I would really appreciate any pointers. Links to articles that explain this well are much appreciated.
Also if anyone knows of any publicly available repositories or projects that have this kind of pattern in them, I would love to see them.
Even when using MVVM I still use some form of a controller and consider ViewModels as basically transformation of data to facilitate the view.
So for me there is still a service or controller layer that completely separates the middle and back end tier from the rest of the architecture.
View models come into play depending on the consumer/app - fetches data from the service tier, transforming the data, validating etc for the purpose of a consumer/app/etc.
I have struggled quite a bit with the same thing. Especially since I’ve used MVC quite a lot.
I think the most important thing to consider is that MVVM is not meant to solve exactly the same things as MVC. You can still implement a controller outside of this pattern to complement it. It also changes quite a lot the general design of the application.
One mean to do it that I have used is to implement the controller as a singleton that can be shared between VewModels. This controller can per example be injected into the ViewModels using dependency injection.
Viewmodels could then for exemple subscribe to events coming from the controller to update.
But this is one way to solve this problem among others.
MVVM is a way to organize code. It’s one way to separate your user interface from your logic.
I have found a blog where you can have a look where MVVM architecture is described perfectly.Though here writer demonstrates MVVM for windows form app but at least you can get some idea about architectural design of MVVM.
https://scottlilly.com/c-design-patterns-mvvm-model-view-viewmodel/
Also please have a look into this repo.
https://github.com/MarkWithall/worlds-simplest-csharp-wpf-mvvm-example
To better show my problem, I drew a graph of how my ViewModel hierarchy looks like so far:
ViewModel hierarchy
What I want to achieve is simply call a method from ScriptEditorViewModel and ask it, if the object, which is currently being edited inside EditObjectViewModel has been specified in the script.
Later I also want to send some information to ScriptEditorViewModel and make it generate a script for the object if it doesn't exist.
ScriptEditorViewModel and ProjectManagementViewModel are 2 separate tabs in my program, which are basically operating at the same time.
Is it possible to do that and if so, is it a good approach?
Note: I'm currently using ReactiveUI as my MVVM framework but any other MVVM solution is also welcome.
When using MVVM pattern, you want to decouple components.
In View part there is xaml with bindings to data and command present in ViewModel.
In ViewModel you should keep data that is presented and logic that does something with that data. It is not the wisest thing to couple multiple ViewModels - keep their logic separated. If you have a command method, all data it deals with should be present in its ViewModel. For anything more complex, you shoud consider communicating with some kind of service or database.
Hence comes the Model part. Here you want to create the model of something you want to store and not necessary present in a View.
I don't know if I understood your problem well, but including a database or any kind of 'persistence layer' into your solution should resolve the problem of accessing specific information. You can create some in-memory storage for start.
I'm trying to learn MVVM and WPF and I'm using the MVVM Light Toolkit. Here's what I'm not fully understanding and maybe it's due to an incorrect architecture of my UI.
What I'm trying to accomplish is pretty simple actually. This is a utility application by the way. I want a window that serves as the 'controller' so-to-say that has a set of buttons. Each button should change the content of a frame. Example: one button loads a 'screen' ( or a 'view' if you will ) that allows the user to configure an 'Agency' which is a custom object. Another button loads a list of Users from the Agency that was in the first 'screen'. This 'Users' view needs to also be loaded in the same frame. In fact, as of right now, the window with all the buttons really is only responsible for loading the 'screens' in the frame. The meat of the application will be within all the separate 'screens'
What I am not understanding is 1) how to let each screen/view know about each other since one is dependent upon the other. It seems that in MVVM the ViewModel shouldn't know about anything. But in my case, I need to pass information around ( such as my Agency ).
If I can get some hints on what I need to look into, that would be great.
Thanks!
Some ideas that might connect some of the dots:
You'll most likely have one viewmodel per view ("screen").
Each viewmodel will contain all of the logic for its corresponding view
Viewmodels can and will know about the models (Agency, Users)
Viewmodels can communicate with each other via the Messenger in MVVM Light
Think of MVVM Light's Messenger as an "application-wide eventing system". When you send a message out from one view model, any other view model can be listening for that message/event and react to it as needed.
Does that help at all? Keep your thoughts coming and I'll keep commenting and I'm sure the community will as well :)
Few things:
each of your screens, should be separate view (eg. user control or new window - I suppose you've done that already)
every part of model (eg. Agency, User) you want to display in your application, should be wrapped with its dedicated view model
your views don't really need to know about each other; you can use commands or events on view models to get rid of those dependencies
view model only needs to know about one thing: model it's building on
it's good to think about view as really simple class, with one single responsibility of rendering content; no logic, no code behind (unless it's purely UI/display related) is something to follow
You can try to prepare your models first (if you haven't done that already), then make view models for them (thinking what properties of models you want to expose to views) and once that's ready, build your views basing on view models. Other way around is also viable option - pick whichever feels more natural to you.
One more thing: since you mentioned you can display several screens in one (I assume) main area, think about equipping your view models with something along the lines of bool IsCurrentlyActive property. This way, you can easily show/hide views with button clicks and still utilize binding mechanism.
They shouldn't know about each other. That is what the Messenger is for controllers and views subscribe to the events they are interested in. That way they don't need to know or care where they event originated.
Hmm Kendrick is faster. What he said.
Also it sounds like you kind of want an Outlook type interface, some navigation that loads other views. I had the same question a while ago. How to do Regions in WPF without Prism?
To better understand the MVVM pattern look at this article: WPF Apps With The Model-View-ViewModel Design Pattern
Also I advice you to look at Caliburn Micro framework.
I'm trying to create an silverlight application using the MVVM design pattern. It's a kind of bank application.
I've watched a lot of tutorials on MVVM but something makes me real confused.
I have about fiwe usercontrols representing my views "TransactionsView", "AccountView" etc and a bunch of models "UserProfile" - containing user password, username and a list of UserAccounts, "UserAccounts" - containing name, balance and a list of AccountTransactions, "AccountTransactions" - containing a name, and ammount.
Should i create one modelview which contains my userprofile or should i create a viewmodel for every view i have? I'm a doing right so far? Or have i got it completley wrong?
Thanks
In MVVM, ViewModels are usually 1-to-1 with Views. There isn't a parity between number of ViewModel and Models, though.
View: UI
ViewModel: Handles changes to view state, forwarding them to the model if/when appropriate. Sends notifications from the underlying program back to the user. It may also do initial UI validation.
Model: Actual "guts" of the application. Algorithms, data storage, system calls etc go here. I put program flow here. I've seen other people put it in the ViewModel. That part is up to you to figure out.
A View always needs a ViewModel, hence 1-to-1 (it could have sub-models, but I'll leave that up to you to decide on/deal with. I'd start off with 1-to-1).
A ViewModel usually needs Models to actually "do work", but how many classes/instances is up to each app/problem you're trying to solve.
From what you explain you are going in the right direction. What viewmodel you create is a bit up to you, MVVM is not set in stone - its just a method. What I found through trial and ERROR was that it was smart to understand it well before digging myself in too deep.
I read many articles that didn't explain MVVM in a way I could understand. Finally I found a couple of articles by Jeremiah Morrill that were straight to the point and easy to understand: Article 1 and article 2.
One ViewModel per view is recommended for MVVM.
There's no real hard and fast rules but essentially there's normally one ViewModel per View. You can get into a situation where you want to share a view model across multiple views but it's rare.
Imagine what you want to see on the screen and each state the screen / controls on the screen might be in, everything that is needed on that particular screen (view) should have a corresponding property in your ViewModel that you can bind the View to. So, this translate to a single ViewModel for a particular View. The ViewModel itself can be tied into one or more model(s) in the back. At least that's how I understand it.
I'm working in a C# project and we are , in order to get some unity across the different parts of our UI, trying to use the MVC pattern. The client is windows form based and I'm trying to create a simple MVC pattern implementation.
It's been more challenging than expected, but I still have some questions regarding the MVC pattern. The problem comes mostly from the n-n relationships between its components: Here is what I've understood, but I'm not sure at all of it. Maybe someone can correct me?
Model: can be shared among different Views. 1-n relationship between Model-View
View: shows the state of the model. only one controller (can be shared among different views?). 1-1 relationship with the Model, 1-1 relationship with the controller
Controller: handles the user actions on the view and updates the model. One controller can be shared among different views, a controller interacts only with one model?
I'm not sure about the two last ones:
Can a view have several controller? Or can a view share a controller with another view? Or is it only a 1:1 relationship?
Can a controller handle several views? can it interact with several models?
Also, I take advantage of this question to ask another MVC related question. I've suppressed all the synchronous calls between the different members of the MVC, making use of the events and delegates. One last call is still synchronous and is actually the most important one: The call between the view and the controller is still synchronous, as I need to know rather the controller has been able to handle the user's action or not. This is very bad as it means that I could block the UI thread (hence the client itself) while the controller is processing or doing some work. How can I avoid this? I can make use of the callback but then how do i know to which event the callback comes from?
PS: I can't change the pattern at this stage, so please avoid answers of type "use MVP or MVVC, etc ;)
Thanks!
Model, View, and Controller are conceptual layers, not individual objects, so honestly it doesn't make a whole lot of sense to be thinking of them in terms of multiplicities. Nevertheless, I can try to approximate an answer for you.
A Controller returns a single result for a single action; that result may be an actual view or it may be something else. However, the Controller doesn't really actually have any interaction with the view; all it does is provide one or two pieces of information in its result: The name of the view that should be used and (optionally) the model used to populate. It's up to the View Engine to actually create and bind the view, which is a considerable departure from normal Smart Client UI logic.
A Controller may interact with several different pieces of the Model, or not interact with it at all in some cases; there is no rule for that side of the relationship. In an action result, a Controller has to give back either 0 or 1 instances of a "model", but this may not be the true Domain Model, it could be a View Model.
A View is generally bound to exactly one Model (or View Model), although in some cases a View might simply be content and therefore not bound to anything.
So, in the very crude UMLesque parlance:
Controller:Model = 0..* : 0..*
Controller:View = 0..* : 0..1 (request) or 0..* : 0..* (overall)
View:Model = 0..* : 0..1
This is all specific to ASP.NET MVC. If you were designing your own MVC implementation then obviously you could choose to implement it any way you like. Good luck implementing MVC in WinForms, though; Forms don't behave like Views at all, even patterns like MVP/MVVM are quite difficult (though not impossible, c.f. Microsoft's CAB/SCSF) until you move to WPF.
I´ve implemented the MVC pattern in C#. Don´t know very much about theory, or how it should be, or shouldn´t be. I just think that the pattern is the base idea, and then, you can use this idea in many different ways, depending on your own needs. I´ll tell you about my implementation, and hope it helps you.
**The Model**
Your description is pretty clear, so don´t have much more to said. Here is where I define my bussiness objects. I take advantage of this layer to include objects validation rules.
**The Controller**
In addition to handle the user actions and update the view, I have a Unit Of Work for each controller. I check that the objects in the view pass the validations (defined in the model layer) before commit changes in the Unit Of Work.
In my case, one controller can manage many models, and I like to have only one view in each controller.
Like a suggestion, I´d like to use my Framework with diferent UI, so I have an abstract implementation of Controller, and then I have specific controller implementations for different interfaces (WebForms, WinForms, ...).
**The Views**
In your case, we could call them, simply, the forms, the UI, ... I like to organize my desktop applications as if they were web applications, using tabs. One tab represents one controller, and so on, one view, and one or more models.
In conclussion, and in my case:
n models - 1 controller
1 controller - 1 view
--
n models - 1 view
You're probably over-thinking and over-formalizing it a bit.
Here's how I look at it:
Model: This is the actual thing that does real work.
Controller: This is the thing that sends inputs into the model, so it will do work.
View: This displays the results.
That's it. The easiest analogy to use is a console application - the app is the model, STDIN is the controller, and STDOUT is the view.
Extending that analogy, many GUI apps are built on top of command-line apps by attaching to STDIN/STDOUT. In that case, the things sending data to STDIN are the controller, the things taking data from STDOUT and putting on the window are the View, and the console app is still the model.
It's CS 101 again - input, processing, output. It's only trickier for a GUI app because the input and output are typically on the same window.
You (obviously) don't need to actually have a console app to do this - the separations can be done even in a single process. All the other weird wiring stuff that takes place is just whatever is needed to get this relationship between the parts to work. But the wiring isn't the important bit - the important bit is the separation of responsibilities and logical organization of the code.
So, whether 1 view must map to 1 controller, or any other orthognality issues are secondary. In fact, you should probably just do whatever your problem domain requires, but I'd (as typical) argue against over-eager generalization of code - IOW, don't mush things together that aren't really the same.