The Model-View-Controller Pattern

This is a software architectural pattern which helps in defining the responsibility for each of the components and how they fit together in achieving the overall goal. This pattern is primarily used in building user interfaces and is applicable in many areas,
including developing desktop applications and web applications. But I am going to explain the MVC pattern from the context of web development.

Primarily, the MVC pattern has three components:

  • Model: This component represents your domain data. Note that this is not your database. This model component can talk to your database, but the model only represents your domain data. For example, if you are building an e-commerce web application, the model component may contain classes such as Product, Supplier, and Inventory.
  • View: This component is responsible for what to present to the user. Usually, this component would contain your HTML and CSS files. This may also include the layout information governing how your web application looks to the end user.
  • Controller: As the name implies, the controller is responsible for interacting with different components. It receives the request (through the routing module), talks to the model, and sends the appropriate view to the user.

The following image speaks of the MVC pattern:

This separation of responsibilities brings great flexibility to the web application development, allowing each area to be managed separately and independently.

The Code for ASP.NET Core is as follows:

public class ValuesController : Controller
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}

Basically, each controller is represented by a class derived from the Controller class, although we can also write controllers without deriving from Controller. Each public method of the controller represents actions.

In this case, if we define a GET method (accessed via www.yoursite.com/controller without writing GET), it returns a string array as a response. How these strings are returned depends on the content negotiation.