Separation of concerns
Model-View-Controller is a software architectural pattern that divides the application into three interconnected parts to separate internal representation of information from the ways information is presented and accepted from the user.
- View is responsible for rendering the UI. The views generally do not have logic inside them. Generally a view only needs to know where to take pieces of data from the model and plug them into the correct places inside of its HTML template.
- A view talks to the model that contains all of the data that the view needs to display.
- The controller orchestrates everything. It contains the logic of our application. It is responsible for building the model and selecting the view to be displayed.
When an HTTP request arrives, it will get routed to a controller and then it is up to the controller to talk to the database, the file system, etc. It will put the model together. The controller selects the view that is going to be used to render the model to the user. The view simply picks up that model and renders it.
The controller never interacts with the user interface as that is the job of the view. It also never holds any data or state inside of it that is the job of the model.
Routing
The process of directing an HTTP request to a controller is known at routing. The functionality that implements that processing is inside of System.Web.Routing.
Let’s create a new ASP.NET MVC project. In the Global.asax file you can find the Application_Start method that calls static RegisterRoutes method. The RouteConfig class can be found in App_Start folder of the generated project.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
This is where you can define routes for your application. Routes will map the URLs to a proper controller action (a method in our controller) with parameters.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
With this mapping a URL sth/sth/sth will be mapped to {controller}/{action}/{id} and by default it will be Home/Index. The following URLswill all get mapped to Index action of the Home controller:
http://localhost/ http://localhost/home http://localhost/HoMe/Index