I believe this is a software architecture question.
I have a class (Controller) and some child classes (ControllerA, ControllerB, ControllerC) that inherit from Controller.
Controller has all of the functionality that allows me to connect to controllers, grab data, grab status updates, etc... The only differences between the child classes are that some of the data they are gathering is different from controller to controller.
Here are a couple of problems I believe I'm facing:
Getting similar statuses from the various child controllers (like ConnectionStatus)
Binding the controllers in XAML
Here are some examples of each of those concerns:
1) Having the child controllers in a list named Controllers of type List[Controller] is convenient for when checking the status of the controllers because I can just loop through the list and easily check the status or data.
For example:
foreach (Controller controller in Controllers) {
Console.WriteLine(controller.ConnectionStatus);
}
2) But I'm unsure of how to bind to a specific controller's data if they're all in one list.
For example, let's say a ControllerA object is the first object in the Controllers list:
<TextBlock Text="{Binding Path=Controllers[0].ControllerAData}" />
That doesn't work because ControllerAData doesn't appear in the Controller class.
I could create separate lists for each child controller type (ControllerAs, ControllerBs, ControllerCs), but then it becomes harder to loop through each controller and get their status and data like I've shown in example #1.
What's a good approach to solving these issues?
Thank you!
You can keep the controllers in a list but still bind to individual controllers.
var controllerA = new ControllerA();
controllerList.Add(controllerA);
windowA.DataContext = controllerA;
Within the window you will have binding paths relative to this specific controller. The list remains invisible for the bindings.
Btw.: if you are binding to controllers, shouldn't they be named view models?
Related
I guess I have a pretty standard problem as I want to pass certain data from an asp.net MVC 5 controller to a shared view, in my case navigation.
I have a template that shows username and userpicture in the navigation shared view, so I need to pass the respective data to it.
My layout structure:
Shared\Layout
Shared\Header
Shared\Navigation
%Body%
Shared\Footer
Where the Layout ist the master view and of course I also have my other views like Home\Index.
As you can imagine, I have to show the username and his userpicture in every view except the login/registration or any error views.
These views do not use the layout at all, so everytime a view is rendered using the layout structure, the user is already logged in.
So I was researching about ways to pass data from my controller to the navigation view, although my controller returns the Index view and would appreciate some clarification on their disadvantages and valid choices in my use case:
Use case:
My project has a pretty dumb MVC application that the user can access. Once he logs into the MVC app authenticates the user against the same webapi where it get's it's data from and stores the access token as well as other user details for further requests. I'm not yet sure where to store that data. As far as I understand it, the options would be Cookies, Session and local storage.
As I am pretty new to asp.net, MVC and C# in general, I didn't yet figure out how to make the [Authorize] Attribute work inside the MVC app so it can mark the user as authenticated :/
I guess the key problem is that the MVC app does not have access to the database and therefore cannot check the login and populate the User Identity.
How to transfer data from controller to view:
ViewBag: The easiest way of passing data to the view. It is not strongly typed and can be accessed in all views. I was told it is kind of a bad practise to use it and was advised to use viewModels.
ViewData: seems to be kind of the same thing as viewdata.
ViewModel: A strongly typed model that is passed to the view and needs to be declared in any view that uses it. So if I want to use it in my navigation view, I'd need to declare it there. The big disadvantage of this approach is that every viewmodel needs to have kind of a baseViewModel so they have a common structure which appearently can cause problems later down the road and also prevents me from inheriting other models to populate my viewModelStructure.
Cookies: Obviously I can store data in cookies during login and then access them in the view, but the cookies HAVE to be there so I would not be able to save this information in the session or local storage
Session: I can also store data in the session, but the session expires when the user closes the browser tab.
LocalStorage: This is pretty new to me so I can't judge it.
User Identity: I just discovered that I can also access the user's identity from Context.User.Identity.
Global Filter like the [Authorize] attribute or a custom one: If I understand it correctly, with a global filter I can populate needed data automatically in every controller action and exclude the ones that dont need it like Login/register etc. I'm not yet sure how to apply this way because of my project structure (see above).
RenderAction: I could also call another controller method via the RenderAction helper method to always render that section of the page.
How do you guys solve this problem?
If you need more clarification, please do ask.
Thanks :)
Use a base ViewModel. You can still use inheritance to build up functionality in your view models, they'll all just share a common base view model, as you said.
I'm not sure what problems you envisage with this approach, but I would suggest they're outweighed by the benefit of strongly typed, maintainable view models, that can be used by all your views, including partial views and _Layout.
A suggestion to get you started based on your layout structure:
public abstract class ViewModelBase {
public HeaderViewModel Header {get;}
public NavigationViewModel Navigation {get;}
public FooterViewModel Footer {get;}
public ViewModelBase(HeaderViewModel header, NavigationViewModel navigation, FooterViewModel footer) {
Header = header;
Navigation = navigation;
Footer = footer;
}
}
public class HeaderViewModel {
// properties
public HeaderViewModel(...) {
}
}
public class NavigationViewModel {
// properties
public NavigationViewModel(...) {
}
}
public class FooterViewModel {
// properties
public FooterViewModel(...) {
}
}
I've come across an interesting question during my development. Right now, I use a database-agnostic unit of work layer to abstract the access of data from the actual database dependencies in my ASP MVC 4 web application.
Each individual database project which implements the unit of work interfaces are aware of my business models (models that go directly to/from the database). I'm not too sure how I feel about this approach, but that's not the question I am going to ask.
Should I be using a solution like AutoMapper to convert my business models to/from domain models - models that are passed to the view and used for any work that shouldn't have access to database fields (i.e., IDs)?
For example, consider inside my BusinessModels project, I have the following classes
BusinessModels
/UserAccounts/
User.cs
- ID
- Username
- HashedPassword
- Salt
UserSettings.cs
- IsSubscribedToNewsletter
- AllowDirectEmails
Would it make any sense to bind these User, and UserSettings models into a single model using AutoMapper like so
MyProject
/DomainModels/
User.cs
- Username
- HashedPassword
- Salt
- IsSubscribedToNewsletter
- AllowDirectEmails
for the purpose of views?
This question also extends to non-MVC projects but I feel seeing as I am working on an MVC project it would make more sense to ask it in that tag.
TLDR is there any point in mapping business models/entities to view models or does that provide an unnecessary layer of abstraction? And if so, would the Repositories contain business models, or view models (which map automatically to business models under-the-hood)?
You can use view models for two different things:
rendering a new view (GET action), passing the view model object as the model for the view
receiving data back from the view, in a Post Action (POST action), using the view model as parameter
(I know, the second is arguable. But it's not strange to use the view models for this)
The model for the GET action needs all the properties neccessary to render the View:
the values of the entity you're showing/editing
extra values needed to render the view (for example SelectLists for drop down lists)
Suppose that you have a User which can belong to one UserGroup.
In this case, if you want to edit the user, the model needs:
the User data
a list of UserGroups
I'd use a model like this:
public class EditUserModel
{
public User User {get;set;}
public SelectList UserGroups {get;set;}
}
As you can see, I directly add the User as a property. But I don't add the list of categories as a property, because I don't need the whole list of categories, with all their properties in the view. Besides, if you unit test the controller you can verify that the SelectList is as expected (that couldn't be done if you created the User Groups list in the view)
But, what if you don't need all the properties of the user in the View? Is it worth removing the User property, and add individual properties for Name, Email, JoinedData, Active... ? I think the anser is NO. Imagine you add/remove or rename some of the User entity properties. If you had individual properties in the view model, you'd have to change them as well, before updating the View. And, if you rely on automatic mapping (auto mapper, value injecter) you would't even realized if you make some mistake.
I also said that the view model can be used for posting back data to the controller. So you could do this:
[HttpPost]
public ActionResult Edit(EditUserModel userModel)
If you do so, the model binder will populate the userModel with the values in the form controls. So you'lll get back a half empty model. In this case, the UserGroups list would be null, and, depending on how many of the User's properties you edit, the User could also have many null/non-initialized properties.
To avoid making errors, in some occasions is advisable to create a different model (and probably auxiliary classes) to make it clear what is expected to be posted to the model.
For example, if you have an action to show the whole user data, but which only allows to change its password, you could create a class with two properties: Password, and PasswordConfirmation.
In this case, the view model for the POST could only have the Password and PasswordConfirmation. And derive a model for the GET which has this inherited properties, and also the list of User Groups and the User.
Why inheriting and not using independent classes? Simply beacuse when you use something like Html.TextBoxFor(m => m.User.Name), the Model Binder will be able to set the Name property of the User property, only if the parameter for the post action has the same structure. I.e. if the view model for the get has this structure:
public ChangePasswordModel
{
public string Password {get;set;}
public string PasswordConfirmation {get;set;}
// extra properties, like the list of user groups, the user data...
}
And the model for the post has this structure:
public PostedChanegPasswordModel
{
public User User {get;set;}
}
The content of the input rendered by Html.TextBoxFor(m => m.EditedUser.Name) won't be bound to the User.Name of the PostedEditViewModel.
But if you make this:
public EditUserModel : PostedEditUserModel
{
// extra properties, like the list of user groups
}
the data will be bound without any problem.
In general you have to be careful with the models you use for posting and getting. And I recommend using as many different view models as neccesary.
When to use automatic property mapping to completely new view and different models?
You must have a very strong reason to have different view models. This could be a result of starting the application from outside in (i.e. design first) or because a team is developing the UI before or while the business logie is being implemented.
In this case you can find that the classes for the view models, and the views themselves are already defined, and are quite similart to your entities, but not exactly equal. This is one case when I think it can be good to use mappers.
The other reason to use different classes would be to decouple the interface from the logic. But this usually only happens in the previous case.
Regards viewmodels I treat them like a summary of the data you wish to work with.
So taking from your example, your viewmodel would contain data from both the User and UserSettings classes. Let's say you had a view named UserData.cshtml then I would code it up like so:
public class UserDataViewModel
{
public string Username { get; set; }
public bool AllowDirectEmails { get; set; }
// etc ...
}
public ActionResult UserData()
{
var viewModel = new UserDataViewModel();
viewModel.UserName = "Whatever";
viewModel.AllowDirectEmails = false;
// Or however you get the data for the user.....
return View(viewModel)
}
Hopefully you get the idea. So you are on the right track with merging information from externals classes into one viewmodel class. Bascially tie everything together in the viewmodel class.
I name the viewmodel class the same as the view that it's going to be used for. This can help documentation, as well as make it easier for devs new to the code to follow.
I'm using ASP.NET MVC2 and have various controllers in various areas.
In many of these I need to select a value from a list of values contained in a database; selecting a product or an employee for example.
I'm currently thinking of having a controller dedicated to getting these lists of things for use with dropdownlists etc. This controller would simply query the DAL and serve up JSON objects to be loaded with an ajax call on any view that needed them.
My only concern with this is that my view will be getting data from different controllers at once.
Am I right to be concerned? Is there a better way of setting this up, maybe creating a Product/Employee class especially to create a shared strongly typed partial view from?
Create another class which acts as a middle layer between your controllers and data access code. You can call this class methods from differnt controllers now.
public class ItemService()
{
public static List<Items> GetItems()
{
var items=yourRepositary.GetItems();
return items;
}
}
You can call it from your different controllers now
public ActionResult GetItems()
{
var items=ItemService.GetItems();
return Json(items,JsonRequestBehavior.AllowGet);
}
Best solution imho is to create a custom ActionFilterAttribute that populates the ViewData dictionary with whatever data you need to render on the views. You can then create extensions for ViewDataDictionary to access this info in a type-safe manner from the views, or throw an exception if the ViewData does not contain the data (ie prompting you to add the action filter attribute above your controller method). Using inheritance could get you in a mess further up the road.
Another approach would be to use a base class controller that implements this common functionality, then inherit other concrete controllers (paired with views) from this.
This approach would support a situation where there are lots of different lists, or the lists needed building dynamically in response to input paramters.
The ActionFilterAttribute approach might be better suited to situations where there are fewer, more static lists.
I am Learning ASP.NET MVC and downloaded a couple of sample apps. MusicStore etc...
I am coming from a wpf background where we had the MVVM Pattern.
I have noticed that they used the concept of model and ViewModel.
In MVVM is pretty clear that you bind the view to the ViewModel injecting the model into the viewModel.
In MVC you have a controller but I am not sure and confused how the all ties together,as I cannot see the model injected into the ViewModel
I have the following structure
MyCompany.Entities.dll (All the models go here) EG Product
MyCompany.Dal.dll (All the repositories go here)
MyCompany.Services.dll (called by MyCompany.WebUI.Controller calls MyCompany.Dal)
MyCompany.WebUI.MyApp
MyCompany.Tests
From some of the examples I have seen your Model acts as a ViewModel.Am I correct?
Let's take a controller i have something like
public class ProductController
{
public ProductController(IProductRepository productRepository)
{
//omitted as not relevant
}
}
public class ProductVM
{
public ProductVM()
{
// Shouldn't we inject the model here RG Product
}
}
Is there some N-tier examples out there I can refer to?
Is the concept of ViewModel a valid one in MVC?
What is the standard?
Thanks for any suggestions.
Use ViewModels to simplify the View.
For instance, you might have a deep object graph with Products, Order, Customers, etc - and some information from each of these objects are required on a particular View.
A ViewModel provides a way to aggregate the information required for a View into a single object.
ViewModels also allow for things like data annotations and validation - which does not belong on your model, as your model should stay "domain-specific".
But in reality, ViewModels are nothing more than a simple wrapper for your domain objects.
Use a tool like AutoMapper to map back and forth between your ViewModels and domain models with ease.
Personally I always bind to ViewModels in my Views, never to the domain models, even if it's a single object. Why? Well I like to decorate my ViewModels with UIHints, validation, data annotations. Just the same way your domain models are enriched with domain-specific rules and business logic, so should your ViewModels be enriched with UI-specific logic.
If you simply have a object with a 1-1 representation of your domain model, you are missing the point of ViewModels.
Add to the ViewModels only, and nothing more, what is required for a particular View.
Example controller action
public ActionResult CustomerInfo(int customerId)
{
// Fetch the customer from the Repository.
var customer = _repository.FindById(customerId);
// Map domain to ViewModel.
var model = Mapper.Map<Customer,CustomerViewModel>(customer);
// Return strongly-typed view.
return View(model);
}
The difference between MVC and MVVM is that MVC has one set of classes for the data entities. In MVVM you have 2 - one set for binding to your views, and one set for managing the data persistence (which could be in a separate WCF service for example).
The benefits of MVVM are that the model bound to the views is relevant to the UI and completely independant from the persistence Model.
Which to use? Well it depends on how closely the data structure required by your Views maps to the structure of the database. When it is similar - it is possible to bind the DataEntities from your DAL directly to your view - this is the classic MVC pattern. However, you gain much with a separate ViewModel as you can extend these classes with View specific behaviour (e.g. Validation) that your DAL should not be concerned with.
For all but the most simple applications, I would recommend use of a separate ViewModel.
Extremely simple,
ViewModel can be the combination of multiple Model classes, to display or transforming the data to and from within the Network, may be via API calls.
However, Model class is nothing but just be specific to any particular entity, Object or strict to a particular Table.
Ex- For "EmployeeViewModel" can be the combinations of Multiple Model Classes i.e. EmpBasicDetails + EmpAddressDetails +EmpExperienceSummary.
Whereas, "EmpBasicDetails" - is specific Model class which contains the Employee Details specifically.
~Cheers,
I am having some trouble understanding the MVC Pattern. I do understand we are trying to decouple the GUI from the business logic, although I'm having problems understanding how.
From what I understood, the View, is what the user sees. So it generally is the window/form. The Controller is inbetween the View and the Model. The Controller will make the data "flow" in both directions. It will also persist state when needed (if I have a wizard with 5 steps, it is the Controller's responsability to ensure they are made in the correct order, etc). The Model, is where the core of my application logic lives.
Is this view correct?
To try to turn this into something more meaningful, I'll try to sketch out a simple example with WinForms(no ASP.NET or WPF, please! - to the java crowd, from what I come to understand, Swing works in a similar way to WinForms!), to see if I get it right, and I'll raise the questions I always come to while doing it.
Let's assume I have a model that contains just a class (just to make it easier. I know it will make the example look dumb but its easier this way):
class MyNumbers {
private IList<int> listOfNumbers = new List<int> { 1, 3, 5, 7, 9 };
public IList<int> GetNumbers() {
return new ReadOnlyCollection<int>(listOfNumbers);
}
}
Now it's time to make my Controller:
class Controller
{
private MyNumbers myNumbers = new MyNumbers();
public IList<int> GetNumbers() {
return myNumbers.GetNumbers();
}
}
The View should just have a ListBox that has as items all the numbers retrieved in MyNumbers.
Now, the first question arises:
Should the Controller be responsible for creating MyNumbers? In this simple case, I think its acceptable(as MyNumbers will do exactly the same, no matter what, and has no associated state). But let's assume I would want to use for all the different Controllers my app has the same instance of MyNumbers. I would have to pass to this Controller(and all others that need it) that instance of MyNumbers that I want to use. Who is going to be responsible for that? In this WinForms examples, would that be the View? Or would that be the class that creates the View?
Turning the question around: what is the order of instantiation of these 3 parts? What is the code that the "owner" of the MVC called to create it?
Should the Controller create both the View and Model? Should the View instantiate the Controller and the Controller the Model?
Second question:
How is the main method supposed to look like, assuming I only want my application to have the Use Case this Controller portrays?
Third:
Why does in the following MVC diagram, the View have an arrow to the Model? Shouldn't the Controller be always the bridge between both View and Model?
I'll have one or two more questions, but they probably will make more sense asked after I understand this first detail. Or maybe after I understand that first question all the others tear apart.
Thanks!
The easiest way to get a handle on MVC is to use it in a framework that enforces it, that being said..
The Model interacts with the datasource (DB or whatever) and gives you access to your data.
The View interacts with the outside world, it receives input from somewhere and hands off the data to the Controller it also listens to the Controller to make sure its displaying the correct data.
The Controller is where all the magic happens; the Controller manipulates data, pushes events, and handles changes in both directions (to/from the View and to/from the Model).
This diagram is very helpful (it makes much more sense than Wikipedia's):
Source, and a great article on MVC!
As for the criticism within my post I thought I would give a post on how i tend to create an MVC Pattern in PHP
Within PHP i spit the framework up into several sections, of witch some are the normal when it comes to MVC.
Primaries:
Controller
Model
View
Secondariness
- ModelLayer
ViewLoader
Library
ErrorLayer
Within the controller I usually allow all access the secondary layers and the View and Model from Primary.
Here's the way I would structure it
|---------| |------------| |------------|
| Browser | ----> | Controller | ----> | Model |
|---------| |------------| |------------|
| | | |
| | |----------------|
| |
| |------------|
-------------| View |
|------------|
From my diagram I usually bypass the View <-> Model connection and do a Controller <-> Model and then the link from Controller <-> View assigns the data.
Within my framework I tend to create a object storage system so that i can easily fetch objects and so forth. an example of my object storage is like so
class Registry
{
static $storage = array();
public static function get($key)
{
return isset(self::storage[$key]) ? self::storage[$key] : null;
}
public static function set($key,$object)
{
self::"storage[$key] = $object;
}
}
Somewhat more advanced by that's the outline, so with this when I first initialize objects i store them like Registry::set("View",new View()); so that there always accessible.
So within my controller witch is the base controller i create several magic methods __get() __set() so that any class that extends the controller I can easily return teh request for example:
abstract class Controller
{
public function __get($key)
{
//check to make sure key is ok for item such as View,Library etc
return Registry::get($key); //Object / Null
}
}
And the user controller
class Controller_index extends Controller
{
public function index()
{
$this->View->assign("key","value"); // Exucutes a method in the View class
}
}
The model will also be placed into registry but only allowed to be called from ModelLayer
class Model_index extends ModelLayer_MySql
{
}
or
class Model_index extends ModelLayer_MySqli
{
}
or filesystem
class Model_file extends ModelLayer_FileSystem
{
}
so that each class can be specific to the storage type.
This is not the Traditional type of MVC Pattern but it can be called Adoptive MVC.
Other objects such as the View Loader should not be placed into registry as there not specifically for the users interests but used by other entites such as View
abstract class ViewLoader
{
function __construct($file,$data) //send the file and data
{
//Include the file and set the data to a local variable
}
public function MakeUri()
{
return Registry::get('URITools')->CreateURIByArgs(func_get_args());
}
}
as the template file is being included in the View loader and NOT the View class it separates the user methods from teh system methods and also allows methods to be used within the views themselves for general logic.
Example of template file.
<html>
<body>
<?php $this->_include("another_tpl_file.php"); ?>
<?php if(isset($this->session->admin)):?>
<?php echo $this->lang->admin->admin_link ?>
<?php endif; ?>
</body>
</html>
I hope my examples help you understand that little bit more.
Answer to the third question:
When the model changes, it notifies the view, then the view gets the data from the model using its getters.
"From what I understood, the View, is what the user sees. So it generally is the window/form. The Controller is inbetween the View and the Model. The Controller will "handle" data in both directions. It will also persist state when needed (if I have a wizard with 5 steps, it is the Controller's responsability to ensure they are made in the correct order, etc). The Model, is where the core of my application logic lives."
This is almost correct. The controller doesn't persist data. It calls a service that persists data. The reason is, persisting data is never just a call to save. You might want to do validation checks on the data to make sure it is sane according to your business needs. You might want to do some authentication to make sure the data can be saved by a user. If you do that in a service, then you have a nice bundle of functionality that you can use over and over again, say for a webapp and a web service. If you do it in a controller, say for a web app, when you go to write your web service you will have to refactor and/or duplicate code.
In response to your comment "I am not sure I totally understood your point. Does the Controller check UI input, or is the Model that does it?"
You controller should only control which business functionality paths get executed. Thats its. Controllers should be the easiest part of the code to write. You can do some validation on the gui (i.e. view, e.g. like making sure email addresses are properly formatted, text inputs dont exceed maximums), but the business layer should also validate the input -- for the reason I mentioned earlier, that when you start standing up more endpoints, you don't have to refactor.
Should the Controller be responsible
for creating MyNumbers?
I would say 'definitely not.'
If the MVC pattern is designed to decouple the M, V, & C elements, how can this work if the C simply instantiates the M with new MyNumbers()?
In Java, we would use something like the Spring Framework here. You need a way to express the dependency relationship -- or rather the details of how it gets fulfilled -- in a configuration file or other suitable place (i.e. not in compiled code).
But there is another element to this issue: you probably shouldn't define the myNumbers variable (inside C) with the concrete, runtime type you intend to use. Use an interface or an abstract class, and leave it open as to what the actual runtime type is. This way, in the future you can re-implement the IMyNumbers interface to satisfy emerging requirements (those you don't know today) and your C component will continue to work perfectly, none the wiser.
This is from Java, but hopefully it will help.
For the main:
public static void main(String[] args)
{
MyNumbers myNums = new MyNumbers(); // Create your Model
// Create controller, send in Model reference.
Controller controller = new Controller(myNums);
}
Your controller needs a reference to your model. In this case, the controller actually creates all the Swing components. For C#, you may want to leave the form initialization here, but the View/Form needs a reference to the Model (myNums) and the Controller (controller). Hopefully some C# people can help on this front. The View also needs to register as an Observer of the Model (see Observer Pattern).
Here is the constructor I have (adjusted for your case):
public NumberView(Controller controller, MyNumbers myNums)
{
this.controller = controller; // You'll need a local variable for this
this.myNums = myNums; //You'll need a local variable for this
myNums.registerObserver(this); // This is where it registers itself
}
The View passes the work to the Controller to handle the user's actions (buttons, whatever). The Controller decides what to call/do in the Model. In general, the Model then does something and changes its state(maybe more numbers in your list. Whatever it does). At the point, the Model will let its Observers know it has changed and to update themselves. Then the View goes and gets the new data and updates itself. That is why the Model and View talk (your 3rd question).
So the Model will have:
public void notifyObservers()
{
for (Observer o: observers)
{
o.update(); // this will call the View update below since it is an Observer
}
}
So in the View, you'll have something like this:
public void update()
{
setListBox(myNums.getNumbers()); // Or whatever form update you want
}
Hope that helps. I know it is Java, but the concept still applies. You'll have to do a little reading on the Observer pattern to fully get it. Good luck!
I will try to answer this from a relatively less technical stand for what it's worth. I'll try walk through a general example.
Controller controls what view is used. So, say, if you are writing to the page the controller will direct you to the input view (say) while if you are reading the same page it will direct you to it's success view (say).
After one writes to the page the controller will pass those parameters to the relevant model where the logic pertaining to what has to be done with them resides. If there is as error then the controller will direct you to the error view.
My knowledge is based on my one month experience with Agavi. Hope this helps.
Why does in the following MVC diagram, the View have an arrow to the Model? Shouldn't the Controller be always the bridge between both View and Model?
It is the MVC model 2. You can see it usually in Java enterprise application
where CONTROL does the business as well as processes data from/to MODEL and choose which VIEW to render back to client. When rendering to client, VIEW will use data from MODEL:
(source: blogjava.net)
Here is an example how to access data from a JSP(VIEW) file which a bean (MODEL):
class Person {String name;} // MODEL
My name is ${bean.name} // VIEW
View draws the model and represents it to the user
Controller handles the user input and translates them to the modifications into the model
Model holds the data and modification logic
There's no point translating it into code. You won't get it correct straight out anyway.
View
user interface / responsible with input output / some validation / needs to have a way to notify outside world of UI level events
knows only about the model
Model
data structure / represents the data that is presented / should not contain business logic (maybe only some data/structure validation at most)
knows only about himself (think of a Person class that has only Name and Age)
Controller
is responsible for business logic / it crates Views and glues the respective models onto them / has to be able to respond to View events / accesses other layers of the application (persistence / external services / business layers etc.)
knows everything (at least View and model) and is responsible of gluing everything together