How does ASP.NET MVC work? In following post you can learn how it works and that its magic – the loose coupling – comes from convention.
Why do i say magic? Because with the loose coupling of its components Model, View and Controller the code is way more readable and testable (to name only two).
How ASP.NET MVC works
The convention of ASP.NET MVC is that you can set a name in one component just like you want. But you have to repeat this name exactly in the other component.
A home controller
- User clicks on button About, sends get request with URL [Path]/Home/About
- MVC searches for the HomeController
- Retrieves model (in our case empty)
- Looks for the view About
- Browser receives answer from MVC application and shows page with URL [Path]/Home/About
Please click on the image to see it full size:
A list controller
Another typical use case you can find in many tutorials is a list controller. In following example I refer to the tutorial Getting Started with ASP.NET MVC 5 from the ASP.NET page.
The controller handles list overview views and list item views. Lets say the user requests a list item with the id = 1. That means
- User clicks on URL www.yourdomain.com/movies/details/1 –
= sends get request with URL [Path]/[Controller]/[ActionName]/[Parameters]
- MVC searches for the MoviesController
- Retrieves model – in our case a movies database item with the id 1
- Looks for the view Details
- Controller sends the view Details containing the retrieved model (in Razor: code line “@model“) to browser, a page is shown with URL [Path]/movies/details/id
Then you got:
I hope this helped a little bit to clarify how ASP.NET MVC works (it helped me a lot and i use it often when I do some tutorials).
For a beginner tutorial I recommend following ASP.NET MVC Getting Started tutorial: http://www.asp.net/mvc/overview/getting-started/introduction/getting-started
You can find her basics about the MVC execution process: http://www.asp.net/mvc/overview/older-versions-1/overview/understanding-the-asp-net-mvc-execution-process
And if you want to dig deeper here a long post from Scott: 🙂 http://www.hanselman.com/blog/BackToBasicsDynamicImageGenerationASPNETControllersRoutingIHttpHandlersAndRunAllManagedModulesForAllRequests.aspx
* Following article helped me with the diagrams, it is a very good introduction as well:
How MVC works – another simple and helpful introduction: