The purpose of this article is to explain the basics of MVC. Hopefully it will help start with this pattern, in Dot Net, should you never used it before.
What is MVC ? Mvc comes from Model View Controller. This is how the pattern works. A View is just the display of the data. The data itself comes from the Model passed to the View, and the Model gets its data from the Controller.
Let’s see how this works. For the purpose of this article i will be using Visual Studio 2012 and MVC4.
So, let’s start by creating the project :
Hit OK :
Here we select Internet Application and Razor which will be the language used in our Views.
Hit OK and we can finally see our project.
If we run it at this point we can see something working already :
Let’s go back to Visual Studio and look at the way the project is organized.
For now we have 3 folders of interest : Controllers, Models and Views where we will perform most of our work.
Let’s start with Controllers. This is where most of the functionality of our application will reside. Each Controller has a number of actions which will respond to a specific URL.
Each action method has an ActionResult result ( pardon the pun ! ). This tells the system that this action is ready to be invoked and display a View.
What kind of code can we have in a controller ? Well anything that gets the data we would like a view to display.
For now let’s start simple. Let’s create a new controller and call it TestController :
At this point we have a new controller with a bunch of default actions. What we don’t have is Views for them. It is important to understand that controllers / actions map to URLs.
So we could run the project and go to /test/index and we would expect to see something. There’s just one thing left to do create a view for the index action. So let’s go to Views folder, create a new folder called Test ( this is the name of our controller minus the “Controller bit” ). Here we create a view called Index. The engine will do the rest, by default it will look in Views/Test for a view called Index corresponding to our first action.
Now let’s run the project and go to /Test/Index
There, now we can see the new page we created. Granted, it does not do much, but hopefully the relationship between controllers / views and URLs are clear.
This concludes part 1 of this tutorial. In Part 2 we will look at Models and Routes and add some functionality to our project.