Model-View-Controller | MVC

What is MVC?

MVC is an architectural framework that divides an application into 3 logical components: Model, View and Controller. Each of these components have some specific task. MVC architecture allow efficient code reusability and parallel development. MVC application development makes project more scalable and extensive.

Each popular programming language currently use MVC framework for web application development. There may be slight variation in their uses but conceptually all are same.

The model–view–controller architecture illustrates the interactions between them. The model manages the data of the application. It receives user request from the controller. The view represents the model in a particular format. The controller responds to the user request and interacts on the data model objects. The controller receives the input and passes it to the model.

Trygve Reenskaug introduced MVC in Smalltalk-76 in 1970s while visiting the Xerox Palo Alto Research Center. The use of the MVC in web applications became popular after the introduction of NeXT’s WebObjects in 1996, which was originally written in Objective-C. After that MVC pattern became popular among Java developers when WebObjects was ported to Java. Spring frameworks for Java was released in October 2002. Django framework for Python was introduced in July 2005. Rails was introduced in December 2005 for Ruby. MVC web frameworks now hold large market-shares relative to non-MVC web toolkits.

MVC Components

MVC-Framework-MSA-Technosoft

Model-View-Controller, as the name specifies, consists of 3 basic components viz. The Model, the View and the Controller. Let us have a brief description of each MVC component here:

The Model

Model is the central part of the architecture. It deals with data, logic and rules of the application. It is independent of user-interface. It manages business-logic related data or data transferred between view and controller.

The View

View deals with user-interface. It is used for output representation. Same information can be represented in multiple views. It is used for user-interface logic of the application.

The Controller

Controller accepts request from the user, process all the business logics. Controller acts as an interconnection between Model and View. It manipulates data using Model and gives command to View to represent output.

ASP.Net MVC

ASP.NET MVC is a web application framework developed by Microsoft. It is open-source software except ASP.NET Web Forms, which is proprietary.

ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with existing ASP.NET features. Some of these integrated features are master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.

It is an alternative to traditional ASP.NET Web Forms. It is built on the base of ASP.NET so that developers can enjoy almost all the features of ASP.Net while building the MVC application.

ASP.NET MVC was announced in 2007. In April 2009, the ASP.NET MVC source code was released under the Microsoft Public License (MS-PL). In March 2012, Microsoft had released part of its web stack (including ASP.NET MVC, Razor and Web API) under an open source license (Apache License 2.0). ASP.NET Web Forms was not included in this initiative.

How MVC Application work?

MVC-Application-Working-MSA-Technosoft

 

  • Client browser sends request to the MVC Application.
  • Global.ascx receives this request.Performs routing based on the URL of the incoming request using the RouteTable, RouteData, UrlRoutingModule and MvcRouteHandler objects.
  • Routing operation then call appropriate controller and executes it using the IControllerFactory object and MvcHandler object’s Execute method.
  • Controller processes the data using Model and invokes the appropriate method using ControllerActionInvoker object.
  • The processed Model is then passed to the View to renders the final output.

MVC is an advanced and sophisticated web application framework designed with separation of concerns and testability in mind.

Creating ASP.Net MVC Application

Let us create our first Model View Controller application in ASP.net

Step1: Open Visual Studio in your computer.

Step2: Select File > New > Project.

Step3: Click on Web > ASP.NET MVC Web Application specify Name of your application and set the location C:\MVC then click on OK button.

Step4: Select Project Template Empty and View Engine Razor for your first application. Click on OK button. You are now ready to start working.

Step5: Create your first Controller. Right click on Controller Folder > Add > Controller. Give Name your controller > Add. It will create a class file under controller folder with some default code snippet.

[NOTE: Controller is a class file containing multiple public methods known as Action Methods.]

Step6: Add View to our Controller. Right click on View folder > Add > View. Provide View Name and Select View Engine as Razor (CSHTML). Click on Add button. This will add CSHTML file in View/Home folder with some default code snippet.

Step7: Modify the code according to your choice.

Step8: Run the application. You will see the output of your application in browser.

[NOTE: Model View Controller uses the ViewBag object to pass data between Controller and View.]

MVC Application Example

*MyMVCApp

*Creating Controller MyController.cs

using System;
using System.Web.Mvc;
namespace MyMVCApp.Controllers {
public class HomeController : Controller {
public ViewResult MyFirstView() {
int hour = DateTime.Now.Hour;
ViewBag.Greeting = hour < 12 ? "Good Morning." + DateTime.Now.ToShortTimeString() : "Good Afternoon." + DateTime.Now.ToShortTimeString();
return View();
}
}
}

*Creating View MyFirstView.cshtml

@{
Layout = null;
}

<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>MyFirstView</title>
</head>
<body>
<div>
@ViewBag.Greeting (<b>From MyFirstView</b>)
</div>
</body>
</html>

[NOTE: We are accessing the value of Greeting attribute of the ViewBag object using @ (which would be set from the Controller).]

Run the application. Our code will run the Controller first, set the ViewBag and then render it using the View code to display output.

MVC View Engine

Model View Controller Framework has 2 different view engines: Razor engine & ASPX engine.

Razor Engine

Razor is a markup syntax. It enables server side C# or VB code into web pages. This server side code can be used to create dynamic content when the web page is being loaded. Razor is an advanced engine in comparision of ASPX engine. It was launched in the later versions of Model View Controller.

Code snippet:

@Html.ActionLink("Create New", "UserAdd")

ASPX Engine

ASPX or the Web Forms engine is the default view engine that is included in the Model View Controller Framework since the beginning. Writing a code with this engine is similar to writing a code in ASP.NET Web Forms.

Code snippet:

<% Html.ActionLink("SignUp", "SignUp") %>

Razor is an advanced View Engine because it comes with compact syntax, test driven development approaches, and of course, better security features.

MVC Layout

MVC Layouts are used to provide consistent look and feel to all pages of the web application. It is similar to Master Pages in ASP.Net but provide more functionalities.

We can use following steps to create MVC Layouts in our application:

Step1: Create a sample MVC application with Internet application as Template and create a Content folder in the root directory of the web application.

Step2: Create a Style Sheet named MyStyle.css under the Content folder. This CSS file will contain all the CSS classes necessary for a consistent web application page design.

Step3: Create a Shared folder under the View folder.

Step4: Create MyLayout.cshtml file under the Shared folder. MyLayout.cshtml represents the layout for each page in the application. Right-click on the Shared folder in the Solution Explorer > Add item > click View.

MyLayout.cshtml Code

<!DOCTYPE html>
<html>
<head><meta charset = "utf-8" />
<title>@ViewBag.Title – MSA Technosoft</title>
<link href = "~/favicon.ico" rel = "shortcut icon" type = "image/x-icon" />
<link rel = "stylesheet" href = "@Url.Content("~/Content/MyStyleSheet.css")" /></head>
<body><header><div class = "content-wrapper">
<div class = "float-left">
<p class = "site-title">@Html.ActionLink("MSA Technosoft", "Index", "Home")</p></div>
<div class = "float-right">
<nav><ul id = "menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li></ul>
</nav></div></div></header>
<div id = "body">
@RenderSection("featured", required: false)
<section class = "content-wrapper main-content clear-fix">
@RenderBody()
</section>
</div>
<footer>
<div class = "content-wrapper">
<div class = "float-left">
<p>© @DateTime.Now.Year – MSA Technosoft</p>
</div>
</div>
</footer>
</body>
</html>
  • Url.Content() method specifies path of any file that we are using in our View code. It takes the virtual path as input and returns the absolute path.
  • Html.ActionLink() method renders HTML links that links to action of some controller. The first parameter specifies the display name, the second parameter specifies the Action name, and the third parameter specifies the Controller name.
  • RenderSection() method specifies the name of the section that we want to display at that location in the template.
  • RenderBody() method renders the actual body of the associated View.

Step5: open _ViewStart.cshtml inside Views folder and add the following code snippet

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

Step6: Run the application.

For more blogs, must go though our Tech-Blogs

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.