May 2012

Volume 27 Number 05

Web Dev Report - Integrate HTML5 into Existing ASP.NET Web Forms and ASP.NET MVC Applications

By Rachel Appel | May 2012

Both public and line-of-business (LOB) applications and Web sites are using HTML5 and related technologies. HTML5 is more than just hype, and it’s more than just HTML. HTML5 and related Web development technologies governed by the W3C enable you to take advantage of some great features that make developing Web applications easier for you and consuming them friendlier for your users. Here are some examples:

  • New HTML elements
  • Geolocation
  • Document object model (DOM) storage
  • Semantic elements
  • HTML5 forms
  • CSS media queries

ASP.NET developers who write LOB applications can easily exploit HTML5 forms because ASP.NET now ships with ASP.NET MVC 4 application templates, which make it easy to integrate HTML5 into Web Forms and previous versions of ASP.NET MVC. HTML5 forms benefit any Web developer because the form elements now support automatic validation of popular data types, resulting in less code to write and maintain. Some new features in HTML5, such as pseudo-elements and pseudo-classes, make your code more maintainable by cutting down on script that would normally run in place of new, more flexible selectors that create the same behaviors.

Make Your ASP.NET Web Forms and ASP.NET MVC Views HTML5 Friendly

Before working with HTML5—or any new technology—it’s natural to want to get good tools that help you write clean and maintainable code. For those using Visual Studio 2010, several extensions and NuGet packages target HTML5, such as the ASP.NET MVC 3 Tools Update and the Web Standards Update. Visual Studio 11 project templates support many HTML5 features out of the box for both ASP.NET Web Forms and ASP.NET MVC.

For HTML5 features to work properly in Web Forms or views, you need to replace current <!DOCTYPE> and <html> elements with their HTML5 counterparts. In ASP.NET Web Forms, this code belongs in the master page. In ASP.NET MVC, this code belongs in the _Layoutpage.cshtml layout page. Regardless of the file type, the markup is the same, as demonstrated here:

<!DOCTYPE html>
<html>

If you plan to integrate an HTML5 feature, you need to do feature detection. Not all browsers have the same capabilities or render markup the same way, and some browsers might be requesting your content from a tablet, a phone or some other Internet-enabled device. The sheer volume of HTML5 features that a browser can support, multiplied by the various platforms and devices, makes it a fool’s errand to continue with the customary practice of simple browser detection. You now need to check for browser support feature by feature rather than just checking to see which browser is requesting your pages. Feature-by-feature detection might sound like a lot of work, but it’s easy if you use the right tool. Modernizr is just such a great feature detection tool.

Modernizr is a lightweight, simple, open-source feature detection framework that allows you to check over 40 HTML5 and related features across all popular browsers, with just these few lines of code:

<script type="text/javascript"> 
    if (Modernizr.geolocation) 
        $("p").text("Hello, Modernizd World, I can find you with Geolocation!"); 
  
    if (Modernizr.webworkers) 
        $("p").text("Web workers work wonders on the Web.");  
</script> 
<p>Testing Modernizr</p>

Modernizr creates a Modernizr object with properties you can query, such as those in the preceding code that check for Geolocation and Web workers. Since Modernizr is just JavaScript, you can download it directly from the Modernizr Web site, or you can use NuGet in Visual Studio to add it to any existing ASP.NET project. 

Update Your ASP.NET Web App to Use HTML5 Semantic Layout

An important aspect of Web development is page layout and structure. In the early days of the Internet, HTML developers used tables since they were the only means of structuring a page. Later on, as CSS standardized, positioning with <div> elements became the norm. Although positioning with the CSS box model continues to be the de facto way to position elements, incorporating HTML5 semantic elements into the page structure to more clearly define both the structure and the content is quickly becoming the new norm.

When updating your ASP.NET pages, semantic elements such as the <header>, <footer> and <nav> are the low-hanging fruit—that is, you can easily replace existing <div> elements in Web Forms or ASP.NET MVC with semantic markup. In Web Forms, you replace <div> elements surrounding the <asp:menu> control with the <nav> element, similar to the following code. If the surrounding <div> elements contain special styling, remember to change the styling in the corresponding CSS to style the <nav> element instead. 

 

<nav><!--replaced <div> with <nav> -->
    <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu"
    EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
        <Items>
            <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"/>
            <asp:MenuItem NavigateUrl="~/About.aspx" Text="About"/>
        </Items>
    </asp:Menu>
</nav><!--replaced </div> with </nav> -->

Figure 1 shows a complete layout page template from an ASP.NET MVC 3 Internet application. Both ASP.NET MVC 3 and ASP.NET MVC 4 View templates include semantic markup by default; in ASP.NET MVC 2, however, you need to wrap the <nav> element around <ul> or <ol> elements to create the same effect.

<!DOCTYPE html>
<html class="no-js">
<head >
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/modernizr-2.0.6.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>
            <nav>
                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                </ul>
            </nav>
        </header>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>

Figure 1 ASP.NET MVC 3 layout page templates containing built-in semantic markup

The <section> and <article> elements are more nuanced when defining structure for content. Determining where these go inside a master page or a layout page depends on the exact layout of the page. As a guideline, <section> elements reveal miscellaneous segments of a page, such as a login box, and <article> elements likely contain a wide variety of both static and dynamically created HTML elements.

A nice side effect of using semantic markup is that both computing devices and humans can easily read the markup and understand the meaning faster than in traditional <div> element processing.

You integrate the above-mentioned elements in a common, reusable project template, which is mandatory for a team of ASP.NET developers. The best place to find one is at the HTML5 Boilerplate Web site. HTML5 Boilerplate is a template for download on which you base your master pages or layout pages to ensure that you have the proper vendor prefixes in CSS, a CSS reset, feature detection with Modernizr and other important cross-browser settings.

Use CSS3 for Less Script and More Maintainable Code

When new versions of software or new technologies become available, it’s easy to miss great timesaving or productivity features, especially in the design side of technology like CSS. Developers often see CSS as the realm of designers only and don’t realize that such timesaving features exist. Last month’s Web Dev Report column points out a few things that developers need to know about CSS for more maintainable code. Here are some of the highlights.

New in CSS3, the General Descendant combinator saves you code because it allows you to select any descendant of an element in a single CSS selector rather than resorting to writing script that loops through the child elements searching for a match. For example, the following sample of CSS applies a solid two-pixel blue border around any anchors that sit inside of paragraphs, all in one line of CSS. Notice that the syntax is a single space between the parent and descendant, making the space character the descendant selector.

p a { border 2px solid #000099 }

Other powerful yet simple selectors include substring matching attribute selectors and new pseudo-classes and pseudo-elements. The tools most often reached for to perform substring matching are the good old-fashioned instr, substr or other string manipulation methods. However, a single selector that contains a pseudo-class or pseudo-elements replaces the approximate half dozen lines of code normally required. Figure 2 shows a comparison of the different ways you can highlight alternating rows with CSS and then jQuery and then JavaScript, and demonstrates that CSS is the smallest and cleanest sample.

 

/* CSS3 nth child selector */
tr:nth-child(odd) {
    background-color:#c8c8c8;
}
<!-- jQuery selector -->
<script>
$(function () {
   $("tr:odd").css("background-color", "# c8c8c8");
});
</script>
<!--Traditional JavaScript -->
<script>
window.onload = function () {
   var table = document.getElementById("MyTable");
   for (var i = 0; row = table.rows[i]; i++) {
       row.addClass("background-color", "c8c8c8");
   }
}
</script>

Figure 2 Different ways to highlight table rows

Enhance Your ASP.NET LOB Applications with HTML5 Forms and Features

ASP.NET developers often write LOB, enterprise or other mission-critical applications. Such applications can benefit greatly from using HTML5 features in business verticals as well as in the broad range of applications.

For example, you can use the HTML5 Geolocation API to deliver content to your users, depending on their physical locale, with just a few lines of JavaScript. Or you can use local DOM storage to save data periodically so a user doesn’t lose it while offline. Vertical industries (e.g., shipping and transportation) that rely on geographic data can also integrate HTML5 Geolocation with the Bing Maps API in any type of ASP.NET application. 

You can deliver breadth market LOB functionality by using HTML5 forms and HTML5 validation. Both features ship with the default project templates for ASP.NET MVC 3 and greater, and ASP.NET Web Forms 4 in Visual Studio 11 project templates.

Most Web Forms projects use <asp:TextBox> controls to collect data, along with other Web Forms controls for various form interactions, such as sliders for ranges and calendars for dates. If you want to use HTML5 forms, just add an HTML5 attribute to an existing Web Forms control, similar to the one shown in Figure 3, or replace an existing control completely with a new input type.

Here are some of the new HTML5 input types:

  • Email
  • Tel
  • URL
  • Placeholder
  • Autofocus
  • Min and Max
  • Date and Time
  • Progress and Meter
  • Pattern

Figure 3 demonstrates a simple form element to collect someone’s age (an up/down numeric data type), done in pure HTML5, then ASP.NET MVC, and finally ASP.NET Web Forms, as well as their corresponding visual representation on the client, an up/down numeric text box.

HTML <input id="Age" type="number" /><br/>
MVC @Html.TextBox("Age", "", new { type = "Number"} )
Web Forms <asp:TextBox ID="Age" runat="server" type="number"></asp:TextBox>

HTML5 numeric TextBox samples in multiple technologies

HTML5 numeric TextBox samples in multiple technologies
Figure 3 HTML5 numeric TextBox samples in multiple technologies

Not all browsers currently support HTML5 form elements, so don’t forget to use Modernizr to perform feature detection. Browsers will fall back and display the HTML <input> elements as basic text boxes if they don’t support the precise feature requested.

Both ASP.NET Web Forms developers and ASP.NET MVC developers can enjoy using HTML5 and related features with any ASP.NET technology today. HTML5 isn’t just a bunch of new and shiny toys; many of its features, such as Geolocation and HTML5 forms, work excellently for business applications.


Rachel Appel is a developer evangelist at Microsoft New York City. You can reach her via her Web site at http://rachelappel.com or by e-mail at rachel.appel@microsoft.com. *You can also follow her latest updates on Twitter at @rachelappel.*