Introduction to MVC and goal change – MVC 4 Web Application Tutorial – Second Part – Step 1 –

In this introduction to MVC, we will be looking at this famous pattern, but first some explanations about this goal change. When I started this tutorial, I had only a vague idea about the kind of web application I wanted to build. The “personal Challenge” idea seemed interesting, but after thinking a bit more about it, it does not seem really useful. I decided to embark on something really different, which could potentially be useful to thousands of people, and which, from my research, does not really exists today.

I don’t want to unveil right now what this is about, this will be done once the project actually start and we begin to design the database. For now let me just say that it will be a real world application, unique, free, of course, using a database, latest technologies with HTLML 5, CSS3, JQuery, and so on. The goal is to build a web application, deployed and hosted, available to anyone, hoping it will end up being a useful, succesful tool for those using it

Obviously the problems to solve during this project will be directly linked to this specific application domain, but in the same time, methods and technic used should be generic enough to be useful examples in many other ASP.NET MVC applications.

The methodology used will be as close as possible to SCRUM methods, which means that each step in the developement process (and tutorial) will have to end up with a usable feature, which means that, at the end of each step we should get “something” usable, without being always fully done. We will also use tests where it is meaningful, but maybe not everywhere.

Source code and the whole project  will be available to everyone on GitHub, so it should be easy to follow the evolution and to participate.

This being said, let’s go back to the subject at hand, MVC….

Model – View – Controller Pattern

The main idea behind MVC is to make easier isolation between different parts of the application user interface, principle also known as “SoC”, Separation of Concerns. It’s about making components independent from each other, which has many benefits:

  • Developement: As individual components are designed to not be depending on one another, it’s easier to build them independently. This make also their replacement or substitution easier, eliminating difficulties happening when modification of one component cascade needed change on others.
  • Testability: In the same way, the ability to untie components make writing tests easier. For example, it become possible to replace a query to a database by a function returning a string, to test another part of the application. This becomes very valuable over time, to check that changes made somewhere have no side effects, as tests must always pass. We will have plenty of opportunities to go back to tests during this project.
  • Maintenance: Components isolation also means that, chances are  a modification will have to be made to only one component, eliminating the need to cascade changes in many places to add or modify a feature.

To be clear, the MVC pattern has to do only with the UI, and more generally with decoupling components. In a real application, it will not be the only pattern in use, and each component must be seen in a flexible, non restrictive way. For example, it’s possible to build a MVC application which has no tie to a database, but with web services returning data. It will still be an application built upon the MVC pattern

Model

Or models. It’s a class, or set of classes representing your application domain. Most of the time it encapsulate data objects stored in a database, as well as code to manipulate this data and enforce domain specific rules. Generally it means a layer accessing data (DAL, Data Access Layer) using some tool like Entity Framework or NHibernate, combined with code containing the business logic specific to the application domain.

View

Her job is to transform the model in its visual representation. For a web application it means to generate HTML code, which will be interpreted by the browser. It’s also in the view that we will find JavaScript code. To follow “SoC” principles, the view must exclusively be used to visualize data, and NOT contain any logic linked to application domain.

Controller

It’s the Orchestra Conductor. He control application logic, get requests from view users, transmit them to the model, perform some actions in relation with the model, and send back the result to the view.

Let’s see immediately how those elements are working together in a first basic MVC application.

First MVC 4 Application

In Visual Studio, new project, web, MVC4 Application “MyFirstMVC4App”, then select “basic” template with Razor as View Engine. In solution explorer, you should see something like the screen copy on the left:

2013-10-28 17_36_59-MyFirstMVC4App - Microsoft Visual Studio

Even for the “basic” application, Visual Studio MVC Template generated a bunch of directories, some (Scripts, for example) containing an impressive number of files. MVC relay on the “convention over configuration” principle, and you will see that generated folders matches this.

You can note there is a Controllers folder, a Models folder and a View folder, but they are empty (Not exactly true for Views, but we”ll get back to this later on).

Content folder is made for CSS files and images used by CSS; It already contain a base theme which allow us to start. Scripts contains JavaScript libraries and files.

If we run our application right now with CTRL-F5 to see what happen, we don’t have any compile error, it’s a valid and properly structured application, but at run time, we get a nice HTTP 404 error, resource not found! As already said, in spite of appearances, the application is empty, hence the error.

For someone having already created a site with PHP, ASP or pure HTML, it might seem obvious an Index file need to be created to solve the problem. It’s not the right way with MVC!

What we do need is a Controller. Nothing works without the Director! And not “any” controller. For the same reasons of convention, to have a method found without adding anything after the main url, like with Index.html, the controller need to be named “HomeController”, and the method named “Index”. We will discover why, and how to change this if needed, but for now let’s take care of making this work without errors, before adding features.

Controller

To create our first controller, right click in solution explorer, select Add in the pop-up menu, then Controller in the sub-menu

Name it “HomeController”, then in scaffolding options select Empty MVC Controller. Here is the code generated for you:
2013-10-28 18_08_57-

View

The word View should be in red, which is Intellisense way to tell us it does not find the matching view. If you right-click on this word, the first option on top of the pop-up menu, is to create the view. The next dialog already got view name and options correctly, you just need to accept it. The generated view just has the “Index” word as title, that’s all.

If we run the application again, we don’t have any error this time, and the page show the word “Index”. If you go back to the controller code, the word “View” is not in red anymore. This application doesn’t do much, but she has already all the structure needed for a full, more complex application.

Model

So far we have a Controller and a View, but no Model. For this very simple first application, which is made only to let us understand better how the MVC components work together, we are going to create the simplest Model, with only one property in a class:

Now change the controller to instantiate this class, et set a value to the property. Then pass the model instance to the view:

The view needs to know the type of the object she receive as parameter, which we do with the @model variable. This kind of view is named “strongly typed”.

Conclusion for this first step of the second part

We built a fully functional MVC application, demonstrating (in a super simplyfied manner) how the Model, View, Controller components interact. You can note that loose coupling exists indeed. It’s easy to add properties to the “DummyModel” calls without consequences on the application. You can change the view to improve the look without having to touch actual code.

If you have been following our First Part about HTML, you know our view is not complete. There is no <HEAD> tag, no <BODY> tag either, yet, if you are curious enough to look at the HTML source code with your browser, you will see those tags are there. This due to using the _Layout.cshtml view, which you can find under View, in the sub-directory Shared. We will check how this is working and set the whole look for our site in the second step of this serie.

Code for this first application is simple enough, so that you should be able to duplicate it yourself, so I don’t think its needed to share it on GitHub. I invite you to do so and play a little around this first example, adding properties to the model and methods to the controller.

If you wish to be informed as soon as there is a new post on the site, subscribe to email updates, clicking on the column on the right side.

Please give feedback, remarks and ideas via the comments below.

This work is licensed under a Creative Commons license.

Until next time!

Posted in ASP.NET MVC 4.0, Tutorial
One comment on “Introduction to MVC and goal change – MVC 4 Web Application Tutorial – Second Part – Step 1 –
  1. will says:

    really a great blog !

Leave a Reply

Your email address will not be published. Required fields are marked *

*

NewsLetter

On Site Search

Custom search