The MVC Pattern
Model-View-Controller (MVC) has been an important architectural pattern in computer science for many years. Originally named Thing-Model-View-Editor in 1979, it was later simplified to Model-View-Controller.
It is a powerful and elegant means of separating concerns within an application (for example, separating data access logic from display logic) and applies itself extremely well to web applications.
You'll find MVC in Java and C++, on Mac and on Windows and inside literally dozens of frameworks.
The MVC separates the User Interface (UI) of an application into the following three main aspects.
The Model: A set of classes that describe the data you're working with as well as the business rules for how the data can be changed and manipulated.
The View: Defines how the application's UI will be displayed.
The Controller: A set of classes that handles communication from the user, overall application flow and application-specific logic.
The Road to MVC 4
In the three short years since ASP.NET MVC 1 was released in March 2009, we've seen four major releases of ASP.NET MVC and several more interim releases.
This section describes the contents and background of each of the three major ASP.NET MVC releases.
ASP.NET MVC 1 Overview
In February 2007, Scott Guthrie (“ScottGu”) of Microsoft sketched out the core of ASP.NET MVC when flying on a plane to a conference on the East Coast of the United States. It was a simple application, containing a few hundred lines of code, but the promise and potential it offered for parts of the Microsoft web developer audience was huge.
Even before the official release, it was clear that ASP.NET MVC wasn't your standard Microsoft product. The development cycle was highly interactive. There were nine preview releases before the official release, unit tests were made available and the code shipped under an open source license.
The end result was that the official MVC 1.0 release, including code and unit tests, had already been used and reviewed by the developers who would be using it. ASP.NETMVC 1.0 was released on 13 March 2009.
ASP.NET MVC 2 Overview
ASP.NET MVC 2 was released just one year later, in March 2010. Some of the main features in MVC 2 included:
- UI helpers with automatic scaffolding with customizable templates.
- Attribute-based model validation on both client and server.
- Strongly typed HTML helpers.
- Improved Visual Studio tooling.
There were also many API enhancements and “pro” features, based on feedback from developers building a variety of applications on ASP.NET MVC 1, such as follows,
Support for partitioning large applications into areas
The following provide support for partitioning large applications into areas:
- Asynchronous controllers support.
- Support for rendering subsections of a page/site using Html.RenderAction.
- Many new helper functions, utilities and API enhancements.
ASP.NET MVC 3 Overview
ASP.NET MVC 3 shipped just 10 months after MVC 2, driven by the release date for Web Matrix. Some of the top features in MVC 3 included:
- The Razor view engine.
- Support for .NET 4 Data Annotations
- Better JavaScript support with unobtrusive JavaScript, jQuery Validation and JSON binding
- Use of NuGet to deliver software and manage dependencies throughout the platform
Razor View Engine
Razor is the first major update to rendering HTML since ASP.NET 1 shipped nearly a decade ago. The default view engine used in MVC 1 and 2 was commonly called the Web Forms view engine, because it uses the same ASPX/ASCX/MASTER files and syntax used in Web Forms. It works, but it was designed to support editing controls in a graphical editor and that legacy shows. An example of this syntax in a Web Forms page is shown here.
- <%@ Page Language="C#" MasterPageFile="undefined</Views/Shared/Site.Master"
- Inherits="System.Web.Mvc.ViewPageundefined<MvcMusicStore.ViewModels.StoreBrowseViewModel>"
- %>
- <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
- Browse Albums
- </asp:Content>
- <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
- <div class="genre">
- <h3>
- <em><%: Model.Genre.Name %>
- </em> Albums
- </h3>
- <ul id="album-list"><% foreach (var album in Model.Albums) { %>
- <li>
- <a href="<%: Url.Action("Details", new { id = album.AlbumId }) %>">
- <img alt="<%: album.Title %>" src="
- <%: album.AlbumArtUrl %>" />
- <span><%: album.Title %>
- </span>
- </a>
- </li><% } %>
- </ul>
- </div>
- </asp:Content>
Razor was designed specifically as a view engine syntax. It has one main focus, code-focused templating for HTML generation. Here's how that same markup would be generated using Razor.
- @model MvcMusicStore.Models.Genre
- @{ViewBag.Title = "Browse Albums";}
-
- <div class="genre">
- <h3>
- <em>@Model.Name</em> Albums
- </h3>
- <ul id="album-list">
- @foreach (var album in Model.Albums)
- {
- <li>
- <a href="@Url.Action("Details", new { id = album.AlbumId })">
- <img alt="@album.Title" src="@album.AlbumArtUrl" />
- <span>@album.Title</span>
- </a>
- </li>
- }
- </ul>
- </div>
The Razor syntax is easier to type and easier to read. Razor doesn't have the XML-like heavy syntax of the Web Forms view engine.
Not a new languageRazor is a syntax that lets you use your existing .NET coding skills in a template in a very intuitive way.
Easy to learn: Precisely because Razor is not a new language, it's easy to learn. You know HTML, you know .NET; just type HTML and hit the @ sign whenever you need to write some .NET code.
Works with any text editor: Because Razor is so lightweight and HTML-focused, you're free to use the editor of your choice. Visual Studio's syntax highlighting and IntelliSense features are nice, but it's simple enough that you can edit it in any text editor.
Good IntelliSense: Though Razor was designed so that you shouldn't need IntelliSense to work with it, IntelliSense is useful for things like viewing the properties your model object supports. For those cases, Razor does offer nice IntelliSense within Visual Studio, as shown in Figure 1-1.
.NET 4 Data Annotation Support
MVC 2 was compiled against .NET 3.5 and thus didn't support any of the .NET 4 Data Annotations enhancements. MVC 3 picks up some new, very useful validation features available due to .NET 4 support.
- public class MyObject
- {
- [StringLength(10, MinimumLength = 3)]
- public string Name
- {get;set;}
- }
Unobtrusive JavaScript
"Unobtrusive JavaScript" is a general approach to the use of JavaScript in web pages. Though the term is not formally defined, its basic principles are generally understood to include.
So it is basically separating behavior or JavaScript from presentation or HTML.
Example
- <input type="button" id="btn" onclick="alert('Test')" />
That is not unobstrusive JavaScript because behaviour and presentation are mixed. The onclick shouldn't be there in HTML and should be part of JavaScript itself not HTML.
With the preceding example, you can go unobstrusive like this.
- <input type="button" id="btn" />
JavaScript
- var el = document.getElementById('btn');
- el.onclick = function(){
- alert('Test');
- };
NuGet Package Manager
- NuGet is a free and open source package manager for the .NET Framework.[1].
- NuGet was formerly known as NuPack; the name was changed to avoid confusion with an existing software package called NUPACK.[2].
- NuGet is distributed as a Visual Studio extension and integrated with SharpDevelop and is included in the C# code snippet tool LINQPad.
- NuGet can be used from command line and automated via scripts.
jQuery Validation
MVC 2 shipped with jQuery, but used Microsoft Ajax for validation.
MVC 3 completed the transition to using jQuery for Ajax support by converting the validation support to run on the popular jQuery Validation plug-in.
The combination of unobtrusive JavaScript support and jQuery validation using the standard plugin system means that the validation is both extremely flexible and can benefit from the huge jQuery community.
JSON Binding
MVC 3 included JavaScript Object Notation (JSON) binding support via the new JsonValueProviderFactory, enabling your action methods to accept and model-bind data in JSON format.
This is especially useful in advanced Ajax scenarios like client templates and data binding that need to post data back to the server.
Global Action Filters
MVC 2 action filters gave you hooks to execute code before or after an action method ran. They were implemented as custom attributes that could be applied to controller actions or to an entire controller.
MVC 2 included some filters in the box, like the Authorize attribute.
MVC 3 extended this with global action filters that apply to all action methods in your application.
This is especially useful for application infrastructure concerns like error handling and logging.
MVC 4 Overview
The MVC 4 release is building on a pretty mature base and is able to focus on some more advanced scenarios. Some top features include:
- ASP.NET Web API.
- Enhancements to default project templates.
- Mobile project template using jQuery Mobile.
- Display Modes.
- Bundling and minification.
ASP.NET Web API
ASP.Net Web API VS ASP.Net MVC
- ASP.Net MVC is used to create web applications that returns both views and data but ASP.Net Web API is used to create full-blown HTTP services with easy and simple way that returns only data not view.
- Web API helps to build REST-ful services over the .NET Framework and it also support content-negotiation (it's about deciding the best response format data that could be acceptable by the client. It could be JSON, XML, ATOM or other formatted data), self hosting that are not in MVC.
- In the Web API the request is mapped to the actions based on HTTP verbs but in MVC it is mapped to action names.
- You can mix Web API and MVC controller in a single project to handle advanced AJAX requests that may return data in JSON, XML or any other format and building a complete HTTP service. Typically, this will be called Web API self-hosting.
- Moreover, the Web API is a light-weight architecture and, except for the web application, it can also be used with smartphone apps.
Enhancements to defaults project templates
When you created a new MVC2 project and ran it, you got a white square on a blue background, as shown in the following figure.
In MVC 4, both the HTML and CSS for the default template have been completely redesigned. A new MVC application appears as shown in the following figure.
Adaptive Layouts in Mobile templates
In addition to a more modern design (or, some would say, any thought to design at all), the new template also features support for mobile browsers using adaptive layout.
Adaptive layout is a technique for designing fluid web layouts that respond to differing screen dimensions using CSS media queries.
When the site is viewed at lower than 850px width (such as on a phone or tablet), the CSS automatically reconfigures to optimize for the small form factor, as shown in the mobile emulator in the figure.
Display Modes
Display modes use a convention-based approach to allow selecting different views based on the browser making the request.
The default view engine first looks for views with names ending with Mobile.cshtml when the browser's user agent indicates a known mobile device.
For example, if you have a generic view titled Index.cshtml and a mobile view titled Index.Mobile.cshtml, MVC4 will automatically use the mobile view when viewed in a mobile browser.
Bundling and Minifying
Bundling: It's a simple logical group of files that could be referenced by unique name and being loaded with one HTTP requestor.
Minification: It's a process of removing unnecessary whitespace, line breaks and comments from code to reduce its size, thereby improving load times.
Basically, a developer uses multiple JavaScript and CSS files for modularity, readability and maintainability of code and it's a good practice too. But in some cases it leads to degradation of the overall performance of the website. Because multiple JavaScript and CSS files require multiple HTTP requests from a browser leads to degrade the performance and load time of your web pages.
In real-time, nearly every website uses a Minification technique to improve their load times, but bundling is not used commonly because every page requires a different set of files and the application will also not support as much to make it simpler.
In ASP.NET MVC 4 Microsoft provides the assembly Microsoft.Web.Optimization (namespace: System.Web.Optimization) for Bundling and Minification that is installed by default with the new ASP.NET MVC4 application template as the NuGet package. It allows the application to minify and bundle the files on the fly.
Before applying bundling and minification
After applying bundling and minification.
The Bundle class from Microsoft.Web.Optimization is used to create custom bundles. To create a custom bundle we need to create an object of the Bundle class by specifying a virtual path and using that we can reference the custom bundle and transform the type, whether it is JavaScript or CSS.
In my scenario I need two sets of bundles, one for Index.aspx and another for Create.aspx, so I create two bundles in the Application_Start event.
- Bundle indexBundle = new Bundle("~/IndexBundle", typeof(JsMinify));
- indexBundle.AddFile("~/Scripts/Demo JS Files/JS-File-1.js");
- indexBundle.AddFile("~/Scripts/Demo JS Files/JS-File-2.js");
- BundleTable.Bundles.Add(indexBundle);
- Bundle createBundle = new Bundle("~/CreateBundle", typeof(JsMinify));
- createBundle.AddFile("~/Scripts/Demo JS Files/JS-File-3.js");
- createBundle.AddFile("~/Scripts/Demo JS Files/JS-File-4.js");
- BundleTable.Bundles.Add(createBundle);
And the following code is used to refer in the respective view:
- <script src="<%: Url.Content("~/CreateBundle") %>" type="text/javascript"></script>
Application Templates
First, you have the option to select from several pre-installed project templates.
The Internet Application templateThis contains the beginnings of an MVC web application, enough that you can run the application immediately after creating it and see a few pages. You'll do that in just a minute. This template also includes some basic account management functions that run against the ASP.NET Membership system.
The Intranet Application template
The Intranet Application template was added as part of the ASP.NET MVC 3 Tools Update. It is similar to the Internet Application template, but the account management functions run against Windows accounts rather than the ASP.NET Membership system.
The Basic template
This template is pretty minimal. It still has the basic folders, CSS and MVC application infrastructure in place. The Basic template is intended for experienced MVC developers who want to set up and configure things exactly how they want them.
The Empty template
The Basic template is for calling the Empty template, but developers complained that it wasn't quite empty enough. With MVC 4, the previous Empty template was renamed Basic and the new Empty template is about as empty as you can get. It has the assemblies and basic folder structure in place, but that's about it.
The Mobile Application templateMobile Application template is preconfigured with jQuery Mobile to jump-start creating a mobile only website. It includes mobile visual themes, a touch-optimized UI and support for Ajax navigation.
The Web API templateThe ASP.NET Web API is a framework for creating HTTP. The Web API template is similar to the Internet Application template but is streamlined for Web API development. For instance, there is no user account management functionality, since Web API account management is often significantly different from standard MVC account management. Web API functionality is also available in the other MVC project templates and even in non-MVC project types.