I am interested in general approach for building interactive GUI using MVC3.
The idea is to build set of different components that can be integrated (plugged in) into various scenarios.
Each Component MUST have it's own model definition, controller and views.
Component encapsulates not just the view but also behavior through it's controller.
All internal implementation details, model, behavior, etc... must reside inside component,
so that component becomes independent, modular - black box.
This allows component to be changed without breaking anything in context in which component is used.
Context in which component runs must not make any assumptions about internal details of component implementation.
On the other side the component does not make any assumptions about context in which it will be used.
Finally, the component must provide mechanism to "communicate" or "interact" with outside world. Beside internals, component must provide some kind of "external" interface (like parameters, data, functions, events whatever...) which would allow component to be integrated into execution context.
The Context (or scenario) is part which contains components.
Now, the basic challenge for the context is to manage interaction between components.
Real-world Categories component example:
Component displays list of categories and allows user to perform various actions such as sorting, paging and record selection.
Internally, it has it's own model which stores relevant information like current page, sort, selection, etc...
Internally, it implements all required actions (for basic render, for user actions response, etc...) in it's own controller.
Internally, it handles model state persistence in the view and model state restore in it's own controller.
Real-world Products component example:
Component displays list of products and allows user to perform various actions such as sorting, paging and record selection.
Internally, it has it's own model which stores relevant information like current page, sort, selection, etc...
Internally, it implements all required actions (for basic render, for user actions response, etc...) in it's own controller.
Internally, it handles model state persistence in the view and model state restore in it's own controller.
Real-world Dashboard page (context, scenario) example:
Page displays both Categories and Products components.
Products component displays all products for the currently selected category and thus must provide external interface (parameter or something) to receive selected category identifier from the context.
Categories component must provide some kind of external interface so that context can act when selected category changes and provide selected category identifier for the products component.
Technically, communication approach for page updates would mostly go through AJAX but if this is possible without AJAX, it would be even better.
In the case of AJAX, I would like solution which uses server side controller(s) which decides and renders what should be updated on the client (JSON or something).
I would not like solution in the client script (client side "like" controller) which decides what actions to call and what parts of page to update - this as said in previous paragraph must be decided by controller(s) on the server.
Important: It is not necessarily for the components to work when directly called via some route.
How would you generally implement described system?
I think you need to investigate real projects and see, what approach do you need to use. Try following project and u can find many best practices:
Here u can find implementing of security measures, services, auth and many many useful.
Kigg
http://www.nopcommerce.com/downloads.aspx
http://orchard.codeplex.com/
It's hard to say for me how it's should be implemented. Better to code it. But using of Dependecy Injectction of Views, Controllers, Services, and Repositories are must in your case.
Each controller handles a whole user-machine pattern. That is, roughly, each controller is responsible for orchestrating the user-machine interaction for a user-case(the user-machine patterns that are the result of the analysys phase).
Now if you put "standard behaviours" in controllers who will coordinate the user-machine interaction pattern?
This way you will have "components" without something that coordinate their execution.
In web forms you have pages that coordinates the execution of components put in them...but in Mvc thi coordination role is played by the Controllers themselves.
You can do black-boxes composed of Controllers and Views just if each of them is responsible of a whole user-machine interaction pattern. That is a "Big Components" not a small building blocks, as its is the case when you implement a CMS.
The Orchard CMS use a similar approach. However what you call components are actually pre-defined blocks that play the role of whole sections of the websites being built by the user.
It seems to me that you are trying to achieve something which may not be out-of-the-box compatible with the philosophy of web MVC (other implementations of MVC might support it).
However, if you wanted to go to the trouble of writing a framework on top of ASP MVC, I am sure you could achieve what you want. For example, by using Areas, you could achieve a form of encapsulation of your controllers, view models, and views.
To compose different areas for the same master view, you could write the equivalent of a front controller with its own view that took in a view model - that view model would be primed by the front controller to render actions from the different areas.
You might achieve more mileage by using a client framework such as Backbone.js on top of ASP MVC.
Related
Problem
While developing struts2 application I was asked to implement two pages: the one listing current user's books and the other listing current user's CDs. So I decided to implement two struts2 actions: ListBooks and ListCDs, both of them having standard dispatch result type, pointing to corresponding JSP pages.
Later the client changed his mind and decided that both lists of books and CDs should reside on the same page. So how can I reuse my actions so that I wouldn't need to rewrite any classes.
My attempt
First approach was to use action chaining. So that both actions can contribute their properties to value stack. But then there is a problem: we establish some unnatural order for actions. If I chain ListBooks to ListCDs then invoking ListCDs on its own causes some erroneous behavior - as it will result in a page where both books and CDs should be listed.
Another way was to use action tags. But I don't like it either as it forces separation of my page into multiple JSP parts and generally feels like doing things not in struts2 style.
Questions
So how do I combine my actions to form single page in a "clean way"? The problem seems to be so simple.
Another question spawned by this problem is about struts2 design - do struts2 actions take too much responsibility? Apart from being "single units of work" they are also coupled to presentation level. Everytime I change the structure of my pages I have to think about redesigning my actions. Am I missing something or struts2 really has this type of design weakness?
Struts 2 actions only take too much responsibility if they're designed that way--they should act as a thin bridge between the web and business layers.
Each of the earlier actions should have just had a service to retrieve the items in question. The new action would have both services, and expose the results of the user's books and CDs to the view layer.
Of course they're coupled to the presentation level--they are what determines what's available to the view. In any action-based framework this is the case, whether it's the action itself, the model in a ModelDriven action, a Spring MVC controller returning a view, a Struts 1 action form, request attributes, etc.
The amount of work necessary to support the type of change you describe is almost nothing: move the service from one action to another, and either expose the additional results directly, or add them to the exposed model.
ViewModel is a term that is used in both MVVM (Model-View-ViewModel) and the recommended implementation for ASP.NET MVC. Researching "ViewModel" can be confusing given that each pattern uses the same term.
What are the main differences between the MVC ViewModel and MVVM ViewModel? For example, I believe the MVVM ViewModel is more rich, given the lack of a Controller. Is this true?
A rather challenging question to answer succinctly, but I'll attempt it. (Bear in mind that the answers to these kinds of questions are still the subject of debate amongst developers.)
In MVC, the ViewModel provides all the information necessary for a View to be rendered. The data it contains is created using data defined in the Model. The View reads the ViewModel and renders the output. Input from the View is passed to the Controller, which manipulates the Model, constructs an appropriate ViewModel, and passes this to the View for rendering.
In MVVM, the ViewModel serves the same function as it does in MVC, but it also replaces part of the MVC Controller by providing commands which allow the View to manipulate the Model. WPF databinding manages the updating of the View according to changes in the ViewModel (and this effectively replaces the remaining function of the MVC Controller).
It's been a while since I played UI Design Patterns Bingo.. however let me take a stab at this..
MVVM is just something that MS has come up with... because it helps you to get the most out of WPF. You combine the state and behavior of the view into a class (a presentation model) that is easily testable + then you use data-binding to get the data into any view.
This link has a brief of the evolution of MVVM. Combine this with Fowler's "GUI Architectures" series, and you should be on your way.
Update: Didn't know there was something called MVC-VM. Apparently a brainchild of the ASP.NET MVC crowd. Looks and sounds similar to MVVM (except tuned for ASP.NET MVC); the only difference is that it places a restriction that there is 1:1 mapping between VM and View. I'd have guessed 1:N, but everything else matches.
I know this is a (way) old question, but I've been pointed to it as an example of using "View Model" in the context of MVC. I argue that this is incorrect and can lead to confusion by people who are new to either/or/both patterns. Whoever is doing it--stahp. Here's why (and it's even an answer to the original question in a roundabout way).
An example of when this happens can be seen in this question. The user is trying to use a View Model that implements INotifyPropertyChanged in an ASP.NET MVC application, thus mashing together desktop and stateless web application design in an architectural fail and heartbreak.
To put it simply, there is no "View Model" in the MVC pattern. There is, however, a functional equivalent, and that's the Controller. Just to be clear about the parts and their purpouses,
MVVM (desktop applications):
Model - Strongly typed object that holds data to be passed between the View and View Model
View - The UI viewed by the user and through which the user interacts with the system
View Model - Interprets user actions (e.g., via ICommand), performs them, updates application state
MVC (web applications):
Model - Strongly typed* object that holds data to be passed between the View and View Model
View - A UI generator that combines the Model, code and HTML to render a webpage
Controller - Accepts user requests, interprets them, updates application state and uses a View to convert this state into an HTML webpage
The Model is practically the same in both patterns. Desktop models may implement update event notifications, web Models may be dynamic (i.e., not strongly typed), and both may or may not include validation methods or metadata.
The View in the desktop is what the user sees. In the web, it is a generator that outputs HTML for browsers to display on the client side. It must interpret user interaction on the desktop, but on the web that is handled by client side javascript, the browser, and the requests that are sent back to the server.
The View Model/Controller are roughly functionally equivalent, but differ greatly in how they are implemented and how they operate. In the View Model, user interaction with the application is transferred to View Models via ICommands, routed events, and other methods (many MVVM frameworks provide different ways to hook View Models to the UI and other parts of the application). In a Controller, a request comes in with all information needed for the Controller to return a result to the user (assuming it's a 200 OK request). The Controller must perform whatever work is necessary to create the state (aka Model) needed for the HTML generator (the View) to create the response. Design-wise, the Controller sits above the View and Model knowing and controlling both, whereas the ViewModel sits next to the View, passing the Model (and other information) between them.
What really seems to confuse some people is that there are client side MVVM frameworks that you can mix into your MVC application. These exist solely in javascript in the user's browser, and have nothing to do with whatever particular pattern you're following on the server side. You can run a classic ASP website that uses MVVM on the client side. Hell, you can run static HTML pages that use MVVM on the client side. They are that separate.
These javascript MVVM frameworks typically follow a similar pattern to the desktop MVVM pattern described above, but adjusted to work more in tune with the nature of the HTML DOM and javascript. For example, there is no extensive binding system woven into the DOM, and javascript has a very limited type system, so matching up templates to models is much different than in WPF. They also typically work disconnected from the server, and when they need to interact, prefer AJAX calls rather than POSTing the page back to the Controller (AJAX calls typically are handled by WebAPI Controllers in ASP.NET MVC).
So, to summarize, there really isn't a View Model in MVC. The Controller is the rough equivalent, but is very different in how it receives user input, interprets it, and returns a result to the user. Using the term "View Model" to refer to anything in MVC can only lead to confusion, and therefore should be avoided. Use the proper terms for the proper parts of the pattern. It may seem pedantic, but it should help keep things clear and be less confusing to people who are new to both patterns.
We're building about 10 ASP.NET MVC sites which have a common set of features (and corresponding URLs, Routes, Controllers, Actions, and Views). The sites will also all share a base set of domain objects (e.g. users, companies) and base attributes on those objects (e.g. name, address, etc.).
But each site will also be highly customized and extended from the base. For example, our site for large, public companies will have "Subsidiary" and "Stock Symbol" fields on the Company domain object, while our site for startups will have a "Venture Firm" and and "Funding" attributes. Look and feel will also vary considerably, although we're trying to keep HTML as consistent as possible (modulo extra form fields for extra domain object attributes, etc.). We'll also be overriding images sparingly, so we can, for example, re-use the same button graphics across sites.
Anyway, we're trying to figure out how best to factor and architect things so that we can reuse as much code and as many tests as possible without limiting our freedom to add per-app attributes and vary the UI between apps.
I'm familiar with how to handle limited-customization multi-tenancy like you find in StackOverflow/SuperUser/ServerFault (or MSDN/TechNet for that matter), where the UI is a little different and the data model is more-or-less identical. But when the models and UI are very different (but inherit from a common base), I'm less sure how to proceed.
I'm less worried about operational issues, since we'll probably be running each site in a separate appdomain and hosting them on separate databases. I'm more worried about reducing long-term code maintenance costs, increasing agility (e.g. easy to add new features to the base without breaking derived apps), and realizing short-term dev-/test-cost savings as we build our 2nd, 3rd, 4th, etc. site.
I'm looking both for high-level guidance and suggestions, but also concrete suggestions for how to make that guidance real using modern ASP.NET MVC practices.
I realize this is a very general question, but for starters I'm looking for both high-level guidance as well as concrete tips-n-tricks for how to apply that guidance with ASP.NET MVC, including things like:
recommendations where to split base/derived across Visual Studio projects
source control tips to avoid forking
database schema tips (FWIW, our databases are all small-- under 10K rows per table, so dev/test cost is more of an issue than DB perf)
tips about re-using Controllers/Views/etc. corresponding to the "base" model attributes, especially re-using UI for things like "new customer" forms which will have a mix of base and derived attributes.
Anyone have good advice for how to architect a multi-tenant app like this?
Here's what we do, and it works pretty well for about 8 sites currently.
Define a core MVC project for your Controllers, ViewModels, HttpApplication, routes, etc. This will compile into a DLL and compromise the bulk of your site.
Create a basic set of default views, scripts, images, etc. for your site. These will server as defaults for your individual sites.
Per client, create any custom controllers, routes, etc that you'll need in a project that compiles to another dll.
Also per client, recreate any views, scripts, images that you'll want to use.
To make the above steps work together you'll need to write a little glue. The first piece of glue is a custom view engine. You'll want to customize the standard view engine to first look for views in your client-specific folder, and then the default folder. This lets you easily override the default layout per client.
The second method of getting everything working is to have your core application load the routes, controllers, etc from your client specific assembly. To do this I use the Managed Extensibility Framework (MEF) to expose a single Register method. Calling this method on my client assembly code registers the routes and any other client-specific needs.
Here's a general view of what my site folder structure looks like, with SiteContent being checked for views first:
- AppContent
- AppContent/Static
- AppContent/Static/Images
- AppContent/Static/Scripts
- AppContent/Static/Styles
- AppContent/Views
- AppContent/Views/Shared
- SiteContent
- SiteContent/Static
- SiteContent/Static/Images
- SiteContent/Static/Scripts
- SiteContent/Static/Styles
- SiteContent/Views
- SiteContent/Views/Shared
- web.config
- Global.asax
I have helpers that I can use like SiteImage and AppImage for use in my views. Also, I make each of my client sites use certain specific names for their master pages, that I don't ever define in my AppContent defaults.
I realize this is a rough overview, but it is working well enough for us right now.
I'm involved in a similar type of "suite" of projects currently which is focused on allowing customers to apply for products online but have very similar requirements for what information to collect, where the only differences are around product specific pieces of information or slightly different legislative requirements.
One thing that we have tried to do is create pages (model, view and controller combinations) that are reusable in themselves, so any application can use the page to capture information but redirect to the next page which may be different depending on what type of product is being applied for. To achieve this we are using abstract base controllers in the form of the template method pattern that contain basically all the required controller logic (including action methods with their applied action filters) but then use abstract methods to do the specific stuff such as redirecting to the next page in the process. This means that the concrete implementation of the controller used by specific application page flows may contain only one method which returns a RedirectToActionResult corresponding to the next page in the flow.
There is also quite a bit of other stuff that handles going backwards and those kinds of navigational things, but with the help of action filters you can get it set up that you don't have to worry about it once you get it up and working.
There are also base model objects which contains common functionality, be it validation logic or state persistence logic.
The data captured during the application process is persisted in database as xml serialized model objects which can then be pulled out and de-serialised once the application is completed and spat out in whatever format to whatever system the backend operations staff use to process applications.
The implications of this is that we have a project structure that consists of a base dll that contains top level abstract classes, interfaces and utility classes as well as html helpers, action filters etc. Then we have mvc projects which contain the concrete implementations of the base controllers, models etc as well as the views and masterpages.
The hardest thing is sharing views and I don't think we have properly got this sorted yet. Although with MVC 2.0 containing Areas I think this will become less of an issue but I haven't had a good play with it yet. (see Scott Gu's post on 2.0: http://weblogs.asp.net/scottgu/archive/2009/07/31/asp-net-mvc-v2-preview-1-released.aspx)
One thing I have POCed that looks like it will work is using a base MVC project to contain common views and then extending the default view engine to search that project on the web server when looking for a view to render (which is quite easy to do). Areas though is a far nicer solution.
As for source control, we are using svn and I think you are reasonable in being concerned about branches. It is not something that we have had to deal with yet, but we are probably going to go with git as it seems to make the process of branching and merging much less painful.
Not sure whether this helps you much but I would definitely recommend keep in mind abstract controllers and models, and also look at how you can use html helpers and and partial views to group similar pieces of functionality.
Mike Hadlow goes into good detail on how to accomplish this:
http://mikehadlow.blogspot.com/2008/11/multi-tenancy-part-1-strategy.html
One way to do this is to use branching in a source control system.
The main branch is for the common functionality. You then have a branch for customization and can merge changes out to the customization or back to the main branch.
What are the responsibilities of one vs the other?
What kind of logic should go in one vs the other?
Which one hits services and databases?
How do I decide if my code should go in the viewmodel or the controller?
For the record, I am using ASP MVC, but since the question is architectural, I do not believe it matters what language or framework I am using. I'm inviting all MVC to respond
The ViewModel is a Pattern used to handle the presentation logic and state of the View and the controller is one of the fundamentals parts of any MVC framework, it responds to any http request and orchestrates all the subsequent actions until the http response.
The ViewModel Pattern: More info
In the ViewModel pattern, the UI and
any UI logic are encapsulated in a
View. The View observes a ViewModel
which encapsulates presentation logic
and state. The ViewModel in turn
interacts with the Model and acts as
an intermediary between it and the
View.
View <-> ViewModel <-> Model
The Controllers (Comes from the Front Controller Pattern): More Info
It "provides a centralized entry point
for handling requests."
HTTP Request -> Controller -> (Model,View)
--Plain Differences:--
While the ViewModel is an optional
pattern the Controller is a must, if
you are going the MVC way.
The ViewModel encapsulates
presentation logic and state, The
Controller orchestrates all the
Application Flow.
The ViewModel can be on the client side as well as server side.
Wherever it may be, the sole purpose of viewmodel is to play the
presentation data.
In MVC architecture Viewmodel is not mandatory but with out controller the request from the client cannot be processed.
Controller can be visualised as the main interface between client and server to get any response from the server. It processes the client request, fetches data from repository and then prepares the view data. Viewmodel can be visualised as view data processor/presenter thus an interface to manage the view more eloquently.
In the overall context of a web application we can say the controller is the application request handler whereas viewmodel is only the UI handler.
The Model-View-Controller (MVC) is an architectural design pattern which exists, primarily, to separate business logic from the presentation. Basically, you don't want your back-end touching your front. It typically looks like this:
The reasons for doing this is because, by separating the back-end and the front, you don't tie your user-interface directly to your data/work. This allows you to put new interfaces onto your business logic without affecting said logic. In addition, it also improves the ease of testing.
A simple example of where MVC comes in handy - let's say you have an application that manages your company's finances. Now, if you are correctly using MVC, you can have a front end that sits at some financier's desk and lets him handle transactions, manage the finances, etc. BUT, because the business logic is separate, you can also provide a front-end to your CEO's Blackberry that lets him see the current status of the business. Because the two front-ends are different, they can do different things while still providing (different types of) access to the data.
EDIT:
Since you updated your question a bit, I'll update my answer. There is no perfect science to the separation of MVC. There are some good rules of thumb, however. For example, if you are talking about GUI components, that is probably a view. (Are you talking about look and feel, usability, etc.) If you are talking about data and the "business" side of the house (databases, logic, etc), you are probably referring to a model. And, anything that controls the interaction between the two is most likely a controller.
In addition, it should be noted that, while Views and Models are typically "physically" separated, a controller can exist with a view when it makes sense.
You are correct when you say the framework (or even language) for MVC doesn't matter. The pattern itself is language agnostic and really describes a way to architect your system.
Hope that helps!
I think there's some value to learning received doctrine. But there is also value in understanding how the doctrine came to be the way it is.
Trygve Reenskaug is widely credited with inventing MVC. N. Alex Rupp's article Beyond MVC: A new look at the servelet architecture includes a History of MVC. In a section on Reenskaug's 1978 work at Xerox Palo Alto Research Center, there's a link to his paper Thing-Model-View-Editor: an Example from a planningsystem. There the pieces are described like this.
Thing
Something that is of interest to the user. It could be concrete, like a house or an integrated
circuit. It could be abstract, like a new idea or opinions about a paper. It could be a whole,
like a computer, or a part, like a circuit element.
Model
A Model is an active representation of an abstraction in the form of data in a computing
system
View
To any given Model there is attached one or more Views, each View being capable of
showing one or more pictorial representations of the Model on the screen and on hardcopy. A
View is also able to perform such operations upon the Model that is reasonabely associated
with that View.
Editor
An Editor is an interface between a user and one or more views. It provides the user with a suitable command system, for example in the form of menus that may change dynamically
according to the current context. It provides the Views with the necessary coordination and
command messages.
Rupp identifies Reenskaug's Editor as a Controller or Tool.
MVC Triads emerged in SmallTalk-80. The model was an abstraction of the real-world concept, the view was its visual representation, and the controller was the buttons and slider bars that allowed the user to interact with it (thereby "controlling" the view). All pieces in the triad were interconnected and could communicate with the other two pieces, so there was no layering or abstraction involved. Since then, Reenskaug has "preferred to use the term Tool rather then Controller." According to his notes, these are the terms he has used in later implementations
Some logic and model should be invoked to generate some data (structured or semi-structured). From this data the returned page/JSON/etc. is created, typically with only rudimentary outlining logic.
The first part (creating the data) is done by the controller (via the model usually). The second part - by the View. The ViewModel is the data structure being passed between controller and view, and usually contains only accessors.
Model represents your data and how it's manipulated. Thus, model touches the DB.
View is your UI.
Controler is the glue between them.
MVC stands for Model, View, Controller.
Model = Data (Database tables)
View = HTML, CSS, JavaScript, etc
Controller = Main logic, a contract between Model & View.
In simple and graspable terms,
MVC allows you to develop your applications in a way that your business data and presentation data are separated. With this, a developer and designer can work independently on a MVC app without their work clashing. MVC makes your app avail OOP too.
What is the best way to structure a VB.NET Windows Forms application so that code can be reused and the application can be extended easily?
I used to create lots of new forms. This lead to lots of repeated code and forms which did similar things.
Now, for forms which do similar jobs, such as view/edit/delete items from a specific database table, I create a form with the required controls, have the form create an instance of a class with parameters such as a collection of the controls and a string containing the database table name. Then the individual controls call functions of the class.
Advanced forms will inherit and extend this basic form class.
Has there already been work done in this area?
Are there books / articles available which discuss the options available on this topic?
I had great success with this Passive Screen pattern.
In my opinion, the big problem of the traditional MVC architecture is that people stuff way too much into the form classes. This increases the amount of manual testing you have to do.
The more automated testing you can do after you compile, the more bugs you will catch at your desk. In a complex application, the side effects from even minor changes occur all too often.
The trick to solving this is making a controller assembly that the form assembly (or EXE) references. Every form has a corresponding class in the assembly. Clicking a button will call ThisForm.ThisButton(<args>) which will then fire objects lower in your framework. Each form implements an interface so that, if the controller class needs additional information from the form, it has a interface to retrieve it.
Then for your unit testing you simulate an operator performing complex operations by implementing dummy classes to fire events and feed information to the controller classes. The controller classes don't know any different as the dummy classes implement all the expected interfaces.
There is an important exception and that is for trivial dialogs. For dialogs that have a few check boxes I feel this organization is overkill. I use the command pattern a lot. So in the assembly where I define the Command objects, I put the SIMPLE dialog associated with that command. How simple a dialog has to be to get this treatment is up to you.
I like to structure my applications as follows.
Utility - This is an assembly that has stuff I use all the time - Math functions, file function, etc.
Objects - This has the specific objects I am using for this application.
UIFramework - This defines all form and controller interfaces.
Commands - This has all the Command objects that manipulate my application objects.
UI - Objects that implement the controller interfaces
EXE - Forms that implement the form interface and calls the controller objects.
You may want to check out a Rocky Lhotka's popular CSLA Framework. It provides a very structured way to implement business objects so you can keep the non-UI code out of your forms. Beyond just separating your business logic though, it provides built in n-level undo, validation, security, data binding support, etc.
The one complaint most commonly directed at CSLA is that it makes test driven development difficult, so that may be something to consider as well.
Something that can help a lot is the use of User Controls. With user controls you can reuse the same UI in different forms. Also, you can have many user controls on one form, so if you have a form with a tabcontrol that has 5 tabs, the content of each tab could be a user control, so instead of having hundreds of controls all mixed up in one form, each user control has its own controls and validation logic, and you end up with just six controls in the form: the tabcontrol and the 5 user controls.
This doesn't help in separating UI code from application logic, but it enables you to have small, structured entities instead of forms with thousands of lines of code.