Tuesday 28 October 2014

Top Three Features of ASP.NET MVC 5

ASP.NET MVC is Microsoft’s latest web application development technology based on the principle of the separation of concerns. MVC stands for Models, Views and Controllers, respectively. Prior to MVC pattern, Web Forms was the prime Microsoft technology for web application development. However, Web Forms lacked flexibility of development and loose coupling. MVC addressed these concerns. This article presents brief overview of the top three features offered by ASP.NET MVC 5, which is the 5th version of the Microsoft MVC technology.
1. Attribute Routing
The major difference in ASP.NET MVC and ASP.NET web forms is the way incoming requests are handled.
In Web Forms, incoming requests map to a file or resource on the web server. For instance, the requested URL can be of the form www.abcd.com/xyz.aspx. Here, the URL refers to an ASP.NET Web Form named xyz.aspx, located at the root directory. There is a one-to-one mapping between the URL and the page that is accessed, which must physically reside on the server.
On the other hand, MVC routing pattern maps URLs with action methods, resulting in cleaner and more SEO-friendly URLs (for instance, www.abcd.com/xyz/buy). This URL refers to the action method “buy” of the controller “xyz” on the domain “abcd”.
To see where these routes are configured, go to the solution explorer of your ASP.NET MVC application and find App_Start folder and find the RouteConfig.cs file. It contains a method named RegisterRoutes which takes a collection of type RouteCollection as a parameter. Inside this method are routes that are to be ignored; routes that are to be added can be defined. This is shown in the following code snippet:
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.Option }
      );
}
Apart from defining routes in the RouteConfig.cs file, ASP.NET MVC 5 has introduced a new feature known as attribute routing which allows developers to specify a route as an attribute of the action method. To enable attribute based routing, you need to modify the RegisterRoutes method of RouteConfig.cs file as follows:
public static void RegisterRoutes(RouteCollection routes){
     routes.MapMvcAttributeRoutes();
}

To add a route on any action method, you simple have to add an attribute named Route and pass the route as parameter to it. For instance:
[Route("Products/Sports/{id}")]
   public ActionResult GetSportsItems(string id){
      ViewBag.Id = id;
      return View();
   }
2. Default MVC Template replaced by Bootstrap
ASP.NET MVC 5 replaced the default MVC template with a much more flexible and standardize CSS library called Bootstrap. With the integration of Bootstrap in MVC 5, developers have got myriad of styling options right out of the box.
3. Improved Identity Management and third party Authentications
ASP.NET MVC 5 has introduced a more robust, secure, and at the same time, flexible identity management mechanism. Now with MVC 5, developers need not to explicitly manage identity and authentication of the application users. Rather, these features come built-in with the framework and can be easily tweaked to achieve the desired identity and authentication operations. Also, MVC 5 provides authentication and logic features via third party applications such as Facebook, Google and Twitter, all of them right out of the box.

Top 5 Features of ASP.NET MVC Framework 4

ASP.NET MVC framework is designed to create web applications which can be accessed over the URLs like RESTful services. The application layers will clearly be segregated into Views, Models and Controllers. ASP.NET MVC Framework 4 is available as a separate installer for Visual Studio 2010 and comes out of the box with Visual Studio 2012. In this article I will explain my top 5 features or improvements in ASP.NET MVC 4 framework.

1. New Project Templates

There are a couple of new project templates added for ASP.NET MVC Framework version 4 named web API template and mobile application template. In the RC version of the product there was another template called Single Page Application (SPA) template but it was removed during the RTM.

Web API

Web API templates are used to create HTTP services. These HTTP services can be accessed directly by a variety of clients from tablets, and smart phones to normal PC browsers. It also helps the developers to implement RESTFul architecture in an MVC application. This template is a powerful tool since it paves an easy way for developers to create HTTP services utilizing the core ASP.NET MVC capabilities like Routing, Filters, Query composition, etc.

Mobile Application

As usage of the internet over mobile devices is becoming high, most companies started developing mobile specific applications. Microsoft has wisely included the mobile application template, which will support developing a pure mobile ASP.NET MVC web application. It will include the HTML helpers for mobile specific markups, and mobile specific plug-ins like jQuery mobile, etc.
Building Multi-device Apps with Apache Cordova and Xamarin in Visual Studio
Fig 1.0: New ASP.NET MVC 4 Project
Fig 1.0: New ASP.NET MVC 4 Project

2. Adaptive Rendering - ViewPort Tag & @media CSS

The ViewPort is a <meta> tag added to the client razor view, which will ensure that the page content is displayed in an optimum way despite if the client is a mobile device or a desktop. Without the ViewPort <meta> tag the same web page will be displayed on a mobile device as that of the desktop whereas the mobile device has a smaller screen than a desktop. It makes the usability of the application difficult on the mobile device. The below mentioned ViewPort tag solves this problem.
  1. <meta name="viewport" content="width=device-width" />
The ViewPort tag does content resizing only at the page level. If the developer wants to customize each control styling based on the client device then the @media CSS tag can be used. It applies / overrides the CSS based on the size of the client screen.
  1. @media only screen and (max-width: 650 px)
  2.  
  3. {
  4.  
  5.        /*CSS in this section will be applied when the request is made by a device with a screen and the width is less than 650 pixels*/
  6.  
  7.        /*Custom CSS*/
  8.  
  9. }

3. Display Modes

This feature enables the developers to have different sets of views for each device and load them based on who is accessing the web application. This is required when the requirement is to change the view, content, control look or the operations different from device to device.
In order to have the display modes working, the razor views should be named as _Layout.mobile.cshtml and _Layout.cshtml. The idea is to load the former template view when accessed from a mobile device and to load the later one when accessed from a desktop. In the global.asax Application_Start event add the code below and MVC 4 takes care of doing it automatically.
  1. DefaultDisplayMode mobileDisplayMode = new DefaultDisplayMode("mobile")
  2.             {
  3.                 ContextCondition = (context => context.Request.Browser.IsMobileDevice)
  4.             };
  5.  
  6. DisplayModeProvider.Instance.Modes.Insert(0, mobileDisplayMode);

4. Support for Async Controller Actions

The Asp.Net MVC 4 application developed on .net framework 4.5 will support asynchronous action methods. An asynchronous controller action method will return a Task of ActionResult and will use async / await keywords. Below is a sample async action method.
  1. namespace MvcApplication1.Controllers
  2. {
  3.     public class HomeController : Controller
  4.     {
  1. //Asynchronous Action Method of the controller
  2.         public async Task<ActionResult> GreetAsync()
  3.         {
  4.             return View(await GetGreetMessageAync());
  5.         }
  6.  
  7.         private async Task<string> GetGreetMessageAync()
  8.         {
  9.             string greetingText = String.Empty;
  10.             await Task.Run(() =>
  11.                 {
  12.                     greetingText = "Welcome to async MVC action method demo";
  13.                 });
  14.             return greetingText;
  15.         }
  16.     }
  17. }

5. App_Start Folder

Another improvement, which I see with respect to the ASP.NET MVC solution architecture, is the introduction of App_Start folder, which helps in grouping all the code that is used for configuring the behavior of the Asp.Net MVC framework application. In the earlier versions on ASP.NET MVC all the configurations were directly done inside the global.ascx. Below are few of the config files that are added to the folder by default in an internet application template.
a.  AuthConfig.cs
b. BundleConfig.cs
c.  FilterConfig.cs
d. RouteConfig.cs
e. WebApiConfig.cs
ASP.NET MVC 4 also has lot of other features like the OAuth, bundling & minification, etc. I will leave it for the users to explore.

Happy reading!

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...