Introducing ASP.NET MVC 4 New Features

    This article describes the new features of the ASP.NET MVC 4 web framework introduced in the first Developer Preview version.

    Mobile web


    One of the most stable and growing trends in modern development is the trend of the mobile web. Having a mobile version of the site is no longer just an offer of convenient access for some users, but a means of making money and expanding the audience.

    That is why ASP.NET MVC 4 places great emphasis on providing accessibility to a developer who wants to make a mobile version of the site.

    Mobile site - two approaches

    When creating a mobile version of the site, you can use two approaches:
    • create a separate mobile version of the site;
    • add to the main site the ability to correctly display on mobile devices (adaptive layout).
    Both approaches found support in ASP.NET MVC 4.

    Mobile Website Template

    ASP.NET MVC 4 added a new special project template for a mobile site, you can use it to create a separate version of the site that will work on mobile devices (Figure 1).

    image
    Fig. 1. New mobile site template

    After creating a project on the basis of a new template and launching it, you can see the characteristic mobile view in the browser (Figure 2).

    image
    Fig. 2. Presentation of a mobile site.

    At the same time, all the functionality of the standard template is still available: authorization, demo pages, validation for errors. The interface of the new view is based on the jQuery Mobile JavaScript library, which is now part of ASP.NET MVC.

    Using the new template, you can easily create a separate mobile option for your site.

    Adaptive layout and a new default template

    The second option for creating a mobile version of the site is the use of adaptive layout, which changes the presentation depending on the screen resolution. In ASP.NET MVC 4, the standard default web application template was updated, which already uses adaptive layout (Figure 3).

    image
    Fig. 3. New default application template

    In addition to the updated appearance, which has become more attractive in the template, the adaptive rendering approach was used. The idea of ​​adaptive rendering is as follows: as resolution changes, the appearance of the page adjusts to free space, displaying only those elements that make sense (Figure 5).

    image 
    image 
    image image
    Fig. 5. Adaptive markup

    Pay attention to these images. With a decrease in resolution, the markup adapts to new screen settings and, for example, hides redundant design elements, changes the arrangement of elements and key menu items. At low resolutions, the markup is formed in such a way that important content occupies the entire usable area available for display.

    The adaptive layout in the ASP.NET MVC 4 project is based on the new HTML5 and CSS3 standards, in particular the CSS3 Media Queries standard, which allows you to define different CSS rules for certain conditions, for example, different resolutions. Here's how it works: in the Site.css style definition file, you may find the following code:

    @media only screen and (max-width: 850px) 
    {
         header .float-left, header .float-right
         {
             float: none;
         }
    …
    

    The media construct defines a rule that will use nested markup when the condition is met. In this case, the condition is the use of displays and the size of the displayed window up to 850 pixels. Using a similar mechanism and setting rules, you can react very flexibly to various conditions for displaying your site. In addition, a meta tag is defined in the _Layout.cshtml build file:


    which tells the browser to adjust the content to fit the width of the screen.

    In addition to adaptive layout, the updated application template uses other new standards, such as CSS Gradients.

    Another change in the web application template was the introduction of window forms support for login and registration submissions (Figure 6).

    image
    Fig. 6. Registration form window

    This functionality is noteworthy in that when the browser supports scripts, it offers the user to use the form in the form of a pop-up window, and in the absence of scripts, it automatically transfers the user to a separate registration form page (Figure 7).

    image
    Fig. 7. A separate page of the registration form

    This functionality is implemented using the new AjaxLogin.js script file included in the project. The form windows themselves are built on the functionality of the jQuery UI library, which is included in the project by default.

    Display modes

    Earlier we talked only about changes in project templates. In addition to these innovations, ASP.NET MVС 4 added a new functionality at the framework level, designed to simplify the site’s work with mobile devices.

    The new Display Modes feature allows an application to select views based on the type of browser that requested the page. For example, if the desktop browser requests the Home page, then the web application can return the usual Index view, which is formed on the basis of the Views \ Home \ Index.cshtml template. Upon request from the browser, the site will be able to return a special mobile presentation based on the Views \ Home \ Index.mobile.cshtml template.

    This functionality works automatically, it is enough to define an additional template with the * .mobile.cshtml postfix and it will be used for mobile clients. In the same way, you can define the mobile version of _Layout.cshtml - _Layout.mobile.cshtml and the mobile versions of partial views: _MyPartial.cshtml - _MyPartial.mobile.cshtml.

    The charm and power of the new functionality lies in the possibility of expanding and fine-tuning for specific mobile devices, mobile OS, any other conditions. You can register your instance of DefaultDisplayMode by specifying the name that will be used in the name of the view and the condition under which this view will be selected.

    For example, you can add the following code to Application_Startin the Global.asax file:

    DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPhone") 
    { 
        ContextCondition = (context => context.Request.UserAgent.IndexOf 
            ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0) 
    });
    

    This code defines a new type of “iPhone” view and indicates the condition when such a view should be used: when the user client agent line contains the line “iPhone”, which indicates the user's use of the iPhone’s mobile phone. When this condition is met, the Views \ Shared \ _Layout.iPhone.cshtml view will be used.

    You can build a much more complex condition to determine which view needs to be used for a particular query. Now it becomes much easier to customize your site for different devices and mobile operating systems.

    Switch display modes

    A useful feature of a mobile site is the ability to switch to a standard desktop view, in cases where the user lacks the functionality of a mobile site. Sometimes a different situation may arise when the user prefers to work in the mobile version instead of the standard one.

    To provide such a function, ASP.NET MVC 4 introduced a new mechanism for obtaining information about the current context of the request: whether it is standard or overridden. The HttpContext property now contains a number of new methods:

    • HttpContext.SetOverriddenBrowser(userAgentString)- overrides the current line of the browser agent with a new value;
    • HttpContext.GetOverriddenUserAgent()- returns the initial or current value of the browser agent string if there were no overrides;
    • HttpContext.GetOverriddenBrowser() – returns an instance of HttpBrowserCapabilitiesBase that matches the current value of the browser agent string (real or overridden);
    • HttpContext.ClearOverriddenBrowser() - allows you to clear all overrides.
    The override mechanism uses cookies to store on the client side the type of the selected view. Like almost all other parts of the framework, you can replace the storage provider with the presentation type through its functionality. To do this, you just need to override the provider and replace the value of BrowserOverrideStores.Current with your instance .

    Recipes


    Recipes - this is a new opportunity to expand the functions of Visual Studio and your projects for common tasks: code generation, creating forms, scaffolding.

    Let's see how recipes work with a simple example. Create a project based on ASP.NET MVC 4 and use the NuGet package manager to install the MvcHaack.ViewMobilizer package. This package contains a recipe for automatically generating mobile views for all or selected views of your site.

    After installing the package, in the context menu of the Views folder, select Add - Run Recipie (Figure 8).

    image
    Fig. 8. Launching the recipe

    A window for selecting the recipes installed in the project appears before you (Figure 9).

    image
    Fig. 9. Recipe selection window

    Select the View Mobilizer recipe and click OK. An internal recipe mechanism will be launched, which will already display its own form allowing you to select views for creating their mobile versions (Figure 10).

    image
    Fig. 10. The window created by the recipe.

    Select the desired views and click Mobilize! You can set the necessary postfix if you create views for your own display modes (for example, iPhone). The recipe will automatically create the necessary files and add them to the project (Figure 11).

    image
    Fig. 11. Recipe files

    How recipes work

    A recipe is a class library that contains a specially created recipe class and the necessary dialog boxes for setting the parameters of the recipe.

    Recipes can be of different types, but all of them must implement one of the interfaces: IRecipe, IFolderRecipe, IFileRecipe, which are defined in the new Microsoft.VisualStudio.Web.Mvc.Extensibility.Recipes namespace.

    The recipe class must be the exported type of the MEF framework, that is, it must be marked with the [Export (typeof (IRecipe))] attribute. The following is a view mobilizer recipe class created by Phil Haack:

    [Export(typeof(IRecipe))]
    public class ViewMobilizerRecipe : IFolderRecipe {
         public bool Execute(ProjectFolder folder) {
             var model = new ViewMobilizerModel(folder);
             var form = new ViewMobilizerForm(model);
             var result = form.ShowDialog();
             if (result == DialogResult.OK) {
                 foreach (var view in model.SelectedViews) {
                     var file = view.Item1;
                     string mobileFileName = view.Item2;
                     File.Copy(file.FullName, mobileFileName);
                     folder.DteProjectItems.AddFromFile(mobileFileName);
                 }
             }
             return true;
         }
         public bool IsValidTarget(ProjectFolder folder) {
             return true;
         }
         public string Description {
             get { return "A package for creating display mode views."; }
         }
         public Icon Icon {
             get { return Resources.ViewMobilizer; } 
         }
         public string Name {
             get { return "View Mobilizer"; }
         }
    }
    

    Recipes is a powerful new tool that integrates into projects using the NuGet package manager and allows you to accumulate practices for code generation and performing other routine tasks. Over time, thanks to the community and NuGet, there will be many recipes.

    Async support for asynchronous controllers


    The ability to create asynchronous controllers appeared in ASP.NET MVC for a long time. In the new version of the framework, this feature can be used on the basis of powerful asynchronous innovations of the new version of C #.

    Now you can write your method in the asynchronous controller as follows:

    public async Task Index(string city) { 
        var newsService = new NewsService(); 
        var sportsService = new SportsService(); 
        return View("Common", 
            new PortalViewModel { 
            NewsHeadlines = await newsService.GetHeadlinesAsync(), 
            SportsScores = await sportsService.GetScoresAsync() 
        }); 
    }
    

    Pay attention to the use of the new async and await language constructs. They allow this code to execute the newsService.GetHeadlinesAsync and sportsService.GetScoresAsync methods asynchronously.

    In addition to direct support for asynchronous extensions, the framework adds support for timeouts for asynchronous extensions and the ability to cancel the asynchronous operation. To determine the timeout of an asynchronous action in the controller, mark it with the new AsyncTimeout attribute:

    [AsyncTimeout (2500)]

    To display a special view after the timeout expires, use the HandleError attribute:

    [HandleError (ExceptionType = typeof (TaskCanceledException), View = "TimedOut")]

    After the timeout has elapsed, the client will be shown the TimeOut view.

    [AsyncTimeout(2500)] 
    [HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")] 
    public async Task Index(string city, 
        CancellationToken cancellationToken) { 
        var newsService = new NewsService(); 
        var sportsService = new SportsService(); 
        return View("Common", 
            new PortalViewModel { 
            NewsHeadlines = await newsService.GetHeadlinesAsync(cancellationToken), 
            SportsScores = await sportsService.GetScoresAsync(cancellationToken) 
        }); 
    }
    

    In addition, you can define a special parameter of type CancelationToken in order to add the ability to cancel the asynchronous operation (example above).

    Conclusion


    Innovations in ASP.NET MVC 4 presented in the first Developer Preview version demonstrate the desire of developers to respond to modern requests facing web development and offer simple ways to create mobile website representations and simplify work with many mobile devices.

    On the other hand, recipes allow a new extension of the functionality of projects and Visual Studio based on the familiar mechanisms of MEF and NuGet.

    Finally, support for C # 5 asynchronous innovations to create asynchronous controllers and actions will greatly simplify the creation of complex and scalable web applications.

    We examined the innovations of only the first preliminary version of the framework. You can expect that in future versions, ASP.NET MVC 4 developers will get even more features and functions.

    Also popular now: