What really is and how to use Asp.Net Mvc

Since Asp.Net Mvc 1 I’ve seen many developers confused about how to use it. I’m writing this post with the hope that it will be useful for the developers who want to learn about Asp.net Mvc and will clear up some confusion about what it is.

While Asp.Net Mvc is recent, the MVC paradigm is not. If you don’t know what MVC stands for here’s a very quick info. When using MVC you design your application into 3 tiers:

  • Model - responsible for processing and storing data.
  • View - responsible for displaying the data.
  • Controller - responsible for taking user input, sending it to the proper model and selecting which view is shown to the user.

Asp.Net Mvc (or any other MVC framework) is simply providing the plumbing and the tools to develop faster an application according to the MVC paradigm. They don’t impose to do things in a certain way, it’s still very easy to write a code mess using asp.net mvc. It’s up to you, the developer, to maintain the discipline and respect the responsibilities of each tier.

Many developers suffer of the “fat controller” syndrome, that is they handle everything in the controller. They think that the Model is in fact the database or all those objects which hold data and many tutorials just encourage this confusion. They teach you to shove almost everything in the Model directory, where you have some data holder objects (POCOs) used by linq2sql or EF and also by the Views and frankly, this is a confusing MESS! So let’s clear it up now.

The Model is the application layer where you process and store the data. In a complex application, the Model is at least a project itself, without any relation to Asp.net Mvc. The Model is in fact the “engine” of the application, some people call it the “Business Layer”, it’s simply not the database or the ORM, linq2sql, EF etc. It knows how to persist the data, but it does much more than that. And in a properly written application, the Model uses the Repository pattern (so it won’t be tied up to a specific technology) to deal with the persistance.

You need to understand that your Model may be composed of one or many projects and it has little relation with the Model directory. In fact, the Asp.Net Mvc project is just the web interface of your application and it contains Controllers, Views and … View Models. The View Model is the model used by a View and it is not the same thing as the Model. It usually contains some bits of your Model but that’s it. Only in trivial applications and tutorials, they are the same and it’s important to know the difference.

Also, the Controller is not the Model either. Yes, almost everyone knows this, but many developers seem to love to access the database, orm etc from the controller, basically turning the Controller into a Controller-Model hybrid. The Controller job is to send the input to the Model and eventually to tell the Model to store the processed result. That’s it.

In conclusion, Asp.Net Mvc makes it easy for you to write MVC aplication but you have to know what a Model really is and what a Controller is supposed to do. As for tutorials, take them with a grain of salt, they are made to show some neat features but you also learn some not-so-good practices and think that you have to use linq2sql or EF or that a view model is the Model. And don’t start me about the validation, but this post is already long enough.

Thanks for posting Praetor.

I considered doing something similar a while back.

Put simply, the ‘model’ includes anything that isn’t a controller or a view. This includes entities, services, repositories, and any other class responsible for managing or affecting data.

While most organized developers split layers into their own class libraries, it is not completely wrong to put everything in the mvc project’s Model folder. They are collectively the ‘model’ after all.

Though I would encourage using sub-folders to further organize things if you go the single project route.

http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller

Put simply, the ‘model’ includes anything that isn’t a controller or a view. This includes view models, entities, services, repositories, and any other class responsible for managing or affecting data.
While most organized developers split layers into their own class libraries, it is not completely wrong to put everything in the mvc project’s Model folder. They are collectively the ‘model’ after all.

I respectfully disagree with that. The ViewModel is a ‘contract’ between the Controller and the View, it has no place in the ‘real’ Model (the core of the application).

It’s good practice to put the Model (Business Layer) in a separate project so it can be used outside the Asp.Net Mvc application (that’s why the view model has no place in the Model). I’d put the view models in the Model directory though, because they are tied to the asp.net mvc project.

Well, I actually removed that from my post before you replied. =)

However…

I am not totally convinced of that. I think some things are situational. Let me explain.

In some (but not all) of my applications, controllers never call, or are injected with, a repository. The controllers receive services. Those services may receive one or more repositories, and occasionally and additional service.

The controllers communicate with the services in terms of the ViewModels. The services communicate with the repositories in terms of entities.

This may seem strange, but there are two reasons I choose to do things this way.

  1. It makes every controller action have predictable, slim coding.

  2. It transforms the services into a backing API that could potentially be used with more than one controller.

Example:


[HandleError]
public class UserController : BaseController
{
 
private IUserService userService;
 
public UserController(IUserService userService)
{
this.userService = userService;
}
 
[HttpGet]
public ActionResult Edit(int id)
{
return View(userService.CreateUserEditModel(id));
}
 
[HttpPost]
public ActionResult Edit(UserEditViewModel model)
{
ConsumeErrors(userService.ValidateUserEditModel(model));
if (!ModelState.IsValid) return View(model);
userService.ProcessUserEditModel(model);
return RedirectToAction("Index");
}
 
}

Every single action, in every single controller now has this same basic look.

At the same time, for this to work, the ViewModels must defained at, or below, the same level as the services. This makes them part of the ‘model’ for the given scenario.

Also, please consider that the use of ViewModels is not mandated. It’s optional, however promoted it may be. Otherwise, the default project would have an additional folder for ViewModels, but it doesn’t.

Therefore, I would contend that ViewModels are that red headed step child who must choose for himself where he wants to live.

It transforms the services into a backing API that could potentially be used with more than one controller

This. From your example it seems that you want the services to be used by many views, rather than many controllers.

The Model is by definition available for any controller, however the Controller acts as a liaison between the Model and the View. Your approach basically tied the Model to Asp.Net Mvc, the Model can’t be reused “as is” by a desktop application or a webservice.

In a nutshell, your services work very well only if they are used in an Asp.Net Mvc, but IMO a Model should be independent of the web interface. That’s why it’s good practice to use a separate project for it.

I’m not sure why you say that. I see it the other way around. It is now extremely easy to pop off the mvc app and plop a desktop app on it. If the viewmodels were in the mvc app alone, then I’d have to import them, or rewrite them, just for the desktop app. The way it sits, neither the desktop, nor web app, even need to know about entities, since they never see one.

Consider this: If the controllers job is to direct traffic, why would you introduce entities into it? That just adds the task of transforming entities into viewmodels to the controller in addition to directing traffic. A traffic cop just points you down the right road. If it’s congested, he points you down another. He doesn’t take you out of the car, or make you get in another one, and then send you on your way. In this analogy, you are the data, the car is the view model, and the traffic cop is the controller.

There is nothing about my service layer that requires the ues of mvc. Even the errors returned by the validation methods are just enumerable collection of a generic IValidationError.

Can you explain better why you think the above approach ties itself down? Am I missing something?

If MVC offered nothing other than the routing engine I’d be sold. I love routing. I love pointing to a controller and a method instead of a file in a folder. I love it, I say!

Cheers for Mark! I love the KISS principle. =)

Consider this: If the controllers job is to direct traffic, why would you introduce entities into it? That just adds the task of transforming entities into viewmodels to the controller in addition to directing traffic. A traffic cop just points you down the right road. If it’s congested, he points you down another. He doesn’t take you out of the car, or make you get in another one, and then send you on your way. In this analogy, you are the data, the car is the view model, and the traffic cop is the controller.

I see the things like this:

  • Controller receives user input and sends it to Model for processing
  • Model does validation, processing etc
  • Controller populates the view model according to processing result
  • Controller selects a view and passes the viewmodel to it.

The ViewModel contains all the data required for a view. It might contain the user input and some result from the Model. So the View Model knows about the Model, but there’s a trick :slight_smile: It might knows only some interfaces or a light read-only Model. The ViewModel for showing a view doesn’t have to be the same with the user input.

It is now extremely easy to pop off the mvc app and plop a desktop app on it. If the viewmodels were in the mvc app alone, then I’d have to import them, or rewrite them, just for the desktop app.

Are your sure that the new frontend (desktop application, web service etc) has the SAME views organization? Your initial view models are intended for web usage (a desktop app will handle them differently), and a a web service returns result for a web method call which is quite straightforward.

Now, why am I getting the impression that what you call view model is in fact the returned objects from the Model which will be used by a view.

Now, why am I getting the impression that what you call view model is in fact the returned objects from the Model which will be used by a view.

Because in this scenario, they are. They just aren’t entities.

I would like to remind you though, one of the first things I said in this discussion is that some, but not all, of my apps are like this. In fact, most are done in the typical way, using AutoMapper in the controller to make view model assembly easier. I just really like playing the devil’s advocate because it get’s people thinking.

Believe it or not, I’ve even used a third option. Instead of automapper, a couple of my apps have used self building view models. An example is below:

var entities = userRepository.SelectAllSortedByUsername();
var model = UserManagerViewModel.Create(entities);

Of course, the entities don’t linger in the viewmodels. They are just enumerated to add items to the model.Items list:

foreach (var entity in entities) items.Add(UserManagerItemViewModel.Create(entity));

Anyway, the point is this: sometimes a contract dictates things we’d rather do another way. This isn’t exactly a bad thing. It just makes us expand our tolerences and adapt better.

=)

Nice read man, it actually answered the “hybrid” theory that comes with MVC. Hey SP, are you listening? :wink:

I agree with him and ive heard this a lots. The ViewModels are actually Models sent to the View from the controller. The domain models are seperate model entity that we can find in a side project but in same solution.

What would be nice is a complete tutorial for new ppl that integrate patterns such as unit of work, repository etc… with MVC 3 and Entity Framework 4 (or other orm i don’t mind). A working example as a base. I actually try to make one but its not easy at all lol i don’t even know if im applying the patterns correctly.

Hello,

I have gone through your post and as per my view Model is an engine for whole application because it contains the data base of application. The Controller contains control flow logic and coding stuff. View shows the presentation of whole application. The website which are developed in ASP .NET MVC framework are SEO friendly because it takes less time to respond.

According to the wiki on MVC, you are correct, the term Model collectively refers to anything that acts upon, or manipulates the entities. However, we are discussing things from a more architectured perspective. One where we wish to separate the various logic layers of the application into their own projects to enabled reuse. Once you pull the core, domain, persistence and service layers out, all that’s left is the viewmodels (and possibly a few other things like your bootstrapping files).