This article describes the new features of the ASP.NET MVC 4 web framework presented in the first Developer Preview version.
Mobile web
One of the most stable and gaining 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 in ASP.NET MVC 4 great emphasis is placed on the provision of special features to the 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 the main site the ability to display correctly on mobile devices (adaptive markup).
Both approaches found their support in ASP.NET MVC 4.
Mobile Site Template
A new special project template for a mobile site has been added to ASP.NET MVC 4, you can use it to create a separate version of the site that will work on mobile devices (Figure 1).
Fig.1. New mobile site template
After creating a project based on the new template and launching it, you can see the characteristic mobile view in the browser (Figure 2).
Fig. 2. Presentation of the mobile site
However, all the functionality of the standard template is still available: authorization, demo pages, and validation for errors. The interface of the new view is based on the jQuery Mobile JavaScript library, which is now included in ASP.NET MVC.
Using the new template, you can easily create a separate mobile version for your site.
Adaptive Markup and New Default Template
The second option to create a mobile version of the site is the use of adaptive markup, which changes the presentation depending on the screen resolution. In ASP.NET MVC 4, the standard default web application template has been updated, which already uses an adaptive layout (Figure 3).
Fig. 3. New default application pattern
In addition to the updated appearance, which became more attractive in the template, an adaptive rendering approach was used. The idea of ​​adaptive rendering is as follows: as the resolution changes, the appearance of the page adjusts to the free space, displaying only those elements that make sense (Figure 5).

Fig. 5. Adaptive Markup
Pay attention to these images. When reducing the resolution, the markup adjusts to the new screen parameters and, for example, hides unnecessary design elements, changes the location of the 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 markup in the ASP.NET MVC 4 project is based on the new HTML5 and CSS3 standards, in particular, on the CSS3 Media Queries standard, which allows you to define different CSS rules for specific conditions, for example, different resolutions. Here’s how it works: in the Site.css style definition file you can 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 is up to 850 pixels. Using a similar mechanism and setting the rules, you can react very flexibly to different conditions of displaying your site. In addition, a meta tag is defined in the _Layout.cshtml build file:
<meta name="viewport" content="width=device-width">
which tells the browser to adjust the content to the width of the screen.
In addition to adaptive markup, the updated application template uses other new standards, such as CSS Gradients.
Another change in the web application template was the introduction of support for window forms for login and registration views (Figure 6).
Fig. 6. Registration form window
This functionality is noteworthy because with browser support, the browser prompts the user to use a form in the form of a pop-up window, and if there are no scripts, it automatically takes the user to a separate page for logging (Figure 7).
Fig. 7. Separate page of registration form
This functionality is implemented using a new script file AjaxLogin.js, included in the project. The windows of the forms themselves are built on the functionality of the jQuery UI library, which is included in the project by default.
Display modes
Earlier, we only talked about changes in project templates. In addition to these innovations in ASP.NET MVC 4, a new functionality was added at the level of the framework itself, designed to simplify the work of the site with mobile devices.
The new display mode feature (Display Modes) 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 based on 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. Similarly, you can determine the mobile version of _Layout.cshtml - _Layout.mobile.cshtml and the mobile versions of partial views: _MyPartial.cshtml - _MyPartial.mobile.cshtml.
The beauty 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 that this view will be selected.
For example, you can add the following code in
Application_Start in 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 view “iPhone” and indicates the condition when such a view should be used: when the user’s client agent string contains the string “iPhone”, which indicates the user's use of the iPhone mobile phone. If this condition is met, the Views \ Shared \ _Layout.iPhone.cshtml view will be used.
You can build a much more complicated condition for determining which particular representation you should use for a particular query. Now it becomes much easier to customize your site for different devices and mobile operating systems.
Switching 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 there can be another situation where the user chooses to work in the mobile version instead of the standard one.
To provide such a function in ASP.NET MVC 4, a new mechanism was introduced to obtain information about the current request context: whether it is standard or redefined. Now the HttpContext property contains a number of new methods:
HttpContext.SetOverriddenBrowser(userAgentString)-
overrides the current browser agent string 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 save on the client side the type of view that is selected. Like almost all other parts of the framework, you can replace the storage provider of the presentation type through its functionality. To do this, you just need to override the provider and replace the
BrowserOverrideStores.Current value
with your own instance
.
Recipes
Recipes are a new opportunity to expand the functions of Visual Studio and your projects for common tasks: code generation, form creation, scaffolding.
Consider how recipes work on a simple example. Create a project based on ASP.NET MVC 4 and install the MvcHaack.ViewMobilizer package using the NuGet package manager. 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).
Fig. 8. Run recipe
You will see a window with a selection of recipes installed in the project (Figure 9).
Fig. 9. Recipe Selection Window
Select the recipe View Mobilizer and click OK. The internal recipe mechanism will be launched, which will display its own form allowing you to select views for creating their mobile versions (Figure 10).
Fig. 10. Recipe Created Window
Select the desired views and click Mobilize! You can specify 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).
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 specifying the recipe operation parameters.
Recipes can be of a different type, but all of them must implement one of the interfaces: IRecipe, IFolderRecipe, IFileRecipe, which are defined in the new Microsoft.VisualStudio.Web.Mvc.Exhibition 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. Below is the recipe class View Mobilizer 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 are a powerful new tool that integrates into projects with the help of the NuGet package manager and allows you to accumulate practices for code generation and other routine tasks. Over time, thanks to the community and NuGet recipes will be set.
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 an asynchronous controller as follows:
public async Task<ActionResult> Index(string city) { var newsService = new NewsService(); var sportsService = new SportsService(); return View("Common", new PortalViewModel { NewsHeadlines = await newsService.GetHeadlinesAsync(), SportsScores = await sportsService.GetScoresAsync() }); }
Note the use of 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 asynchronous extension timeouts and the ability to cancel the execution of an asynchronous operation. To determine the timeout of an asynchronous action in the controller, it is necessary to mark it with a new attribute AsyncTimeout:
[AsyncTimeout (2500)]
To display a special view after the timeout expires, use the HandleError attribute:
[HandleError (ExceptionType = typeof (TaskCanceledException), View = "TimedOut")]
After the timeout expires, the client will be shown a TimeOut view.
[AsyncTimeout(2500)] [HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")] public async Task<ActionResult> 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 to add the ability to cancel the execution of an asynchronous operation (example above).
Conclusion
Innovations in ASP.NET MVC 4 presented in the first Developer Preview version demonstrate the willingness of developers to respond to modern requests facing web development and offer simple ways to create mobile website views and simplify work with many mobile devices.
On the other hand, recipes make it possible to expand the functionality of projects and Visual Studio in a new way based on the familiar MEF and NuGet mechanisms.
Finally, support for asynchronous innovations of the C # 5 language for creating asynchronous controllers and actions will significantly simplify the creation of complex and scalable web applications.
We reviewed the innovations of the first only preliminary version of the framework. It can be expected that in future versions ASP.NET MVC 4 developers will get even more features and functions.