Posted by: lluppes | April 22, 2012

Book Excerpt – HTML5 Attributes in MVC

The following is an excerpt from my upcoming book “Delivering Mobile-Friendly WebSites With MVC4”.  The book is nearing rough draft completion, and final editing will begin soon – look for it to be available approximately May 19th!  In the meantime, enjoy this very small taste of what you will find in the book.   Lyle

Using HTML5 Attributes in MVC

There are a variety of new HTML5 tags that can prove very useful on a mobile device, which you can specify by setting the “<input type=” parameter.  These include (but are not limited to): email, tel, url, number, search, time, date, month, datetime, and datetime-local.  Many of these have very limited support on mobile browsers (especially on Android browsers), and there are some (like week and color) that don’t work at all on certain mobile platforms like iOS, and others that work on current versions of iOS (5.x) but not earlier versions (4.x).  We’ll discuss a few of them here and see how you can easily use these in your MVC project.

Editor Templates

Here’s an example of the HTML that would create a phone field:

<input type="tel" name="Phone" value="" />

This code will generate a screen on an iOS phone that looks like this:

Notice that the standard keyboard has been replaced with one that is made up of only numbers, which gives the user much bigger buttons and a higher chance of entering the proper information.  In a similar fashion, the “email” and “url” attributes will pop up a keyboard that has letters plus common web address keys like the @ sign, which doesn’t appear on the default keyboard for normal text fields.

Remember how I said in Chapter 4 that some things don’t work when you are using Safari as a mobile emulator? These tags are one of those things.  These special keyboards won’t pop up in the desktop Safari.  Also – most of these number and date picker tags in this section do not work on Android devices at this time.

You can add manually create the HTML to put in that special input type attribute, but in MVC there is a much better way to do this – data annotations.  Let’s start by modifying a model definition:

public class SampleModel
{
 // -- other fields omitted here for brevity…
 [DataType(DataType.PhoneNumber)]
 [Display(Name = "Phone", Prompt = "Phone:")]
 public string Phone { get; set; }
}

When we add the DataType annotation, this will tell MVC that this is a special type of string, and it will be treated differently when composing a view.  However, if you the only thing you do is to add this data annotation, you won’t see anything different – you need one more piece to this puzzle:  Editor Templates. These templates are not supplied with the standard MVC project template, so you must go get them yourself and add them to your project.  These templates must reside in a folder named EditorTemplates under the Shared folder. The templates can be found in the sample code that accompanies the book, or you can get them using a NuGet package (“Install-Package MvcHtml5Templates”). Here’s an example of the templates as installed in a project:

In our model definition, we’ve specified that our Phone field has a DataType of PhoneNumber, so MVC will look for and use the PhoneNumber template when creating the HTML for editing this field.  The PhoneNumber.cshtml file is very simple, and contains only this code:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
 new { @class = "text-box single-line", type = "tel" })

In your view file, all you need to do is use the EditorFor helper on your field and it will automatically generate the updated HTML now.  (Note that if you use the TextBoxFor helper without any special parameters, it won’t work automatically.)

@Html.EditorFor(m => m.Phone)

This combination of model data annotation, Editor Templates, and the EditorFor helper will generate the code that we started with earlier.  MVC does all the hard stuff for us – pretty sweet, huh?

<input type="tel" name="Phone" value="" />

Let’s look at another example – the DateTime helper.  Let’s edit our model again and add a DateTime field:

public class SampleModel
{
 // -- other fields omitted here...
 [DataType(DataType.DateTime)]
 [Display(Name = "Contact DateTime", Prompt = "Contact DateTime:")]
 public DateTime ContactDateTime { get; set; }
}

Next we’ll add a DateTime.cshtml EditorTempate in the Shared folder:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
 new { @class = "text-box single-line", type = "datetime" })

While we’re at it, let’s create a Month.cshtml EditorTemplate too:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
 new { @class = "text-box single-line", type = "month" })

Now we add this field to our View, we can use either of these EditorFor statements:

@Html.EditorFor(m => m.ContactDateTime)
@Html.EditorFor(m => m.ContactDateTime, "DateTime")
@Html.EditorFor(m => m.ContactDateTime, "Month")

When you run this code on your iOS phone, you will get one of these editors:

It looks like a native app, behaves like a native app, but it’s all HTML!

If you want to get this to work on all mobile platforms right now, you will have to investigate using a third party tool like http://mobiscroll.com/.

On your desktop you won’t notice any difference yet.  If you want a nice date picker on your desktop, you will need to go install the jQuery.UI components (if they are not already in your project).  If you have already added the “DateType.Date” data annotation in your model, and you have included the EditorTemplate Date.cshtml, then there are only a few small changes that you need to make.  In your _Layout.cshtml page (or in your Desktop Bundles in the Global.asax if you are doing minification), you will need to include the jquery-ui.min.js and the jquery-ui.min.css files, and you will need to add the following script in the header of the _Layout file to enable the fields:

<script type="text/javascript">// <![CDATA[
$(document).ready(function () {      $('.date').datepicker({ dateFormat: "mm/dd/yy" });    });
// ]]></script>

That’s it – now you will have a nice fancy date picker popup in your application that looks like this (with almost no work on your part!): Before you commit to using these features, you should make sure they are supported on the devices that you want to target.  A couple of good resources to check are:

http://mobilehtml5.org/ – This site lists many HTML5 features and shows which browsers and operating systems support them.

http://www.quirksmode.org/html5/inputs_mobile.html – This site lists some of the specific HTML tags and attributes (like the ones shown in this chapter), and details which mobile operating systems support those tags.

Search Fields

Another handy field type is the search type.  If you want a field that looks like a search field, just add the Search template type on a string field.  In this case we don’t have a Search data annotation that we can add to our model, so we’ll tell the EditorFor helper to use a specific template, like this:

@Html.EditorFor(m => m.SearchTxt, "Search")

The code in the Search Editor Template looks like this:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
 new { @class = "text-box single-line", type = "search" })

The Resulting Screen:

Notice how the field corners are much more rounded than the normal textbox, and how it has a magnifying glass inside the text field?  These are just subtle hints to the user that this is a special field. We won’t go into all of the EditorTemplates here – there are several with many options.  Some work with the EditorFor and data annotations, and some will need a little more manual tweaking.

Special HTML5 Attributes

There are a few other special attributes that you will appreciate.  The Required attribute is a nice HTML5 attribute, but that should be handled by the Required data annotation in your model, so we won’t address it here. One attribute that is very handy is the placeholder attribute.  This will put the light gray text in the textbox field that gives you a hint of what to type, and then that text disappears when you click in the box.  Let’s go back and enhance our Search box, using the TextBoxFor helper so we can easily add an extra attribute.  Remember how I mentioned earlier that the default TextBoxFor helper wouldn’t use a template from the data annotation?  You can specify one by editing the HtmlAttributes.  Since that’s how we need to specify the placeholder tag, we’ll do both the EditorTemplate and the placeholder attribute using the TextBoxFor command.

@Html.TextBoxFor(m => m.SearchTxt,
 new { type= "search", placeholder = "enter search terms" })

The Resulting Screen:

Now you’ve got the “enter search terms” placeholder text in your search field, and once you click in that field and start typing, that placeholder goes away.  In addition, the user gets a nice little clear button on the right hand side of the textbox.  Not bad for one simple little attribute, huh? Other attributes you may want to investigate adding to your text boxes are autocorrect=”off”, autocomplete=”off”, autocapitalize=”off”.  There are plenty of autocorrect gaffes out there, and we may want to help our users avoid being one of those.  (Then again, those gaffes are pretty amusing…!)

Written by .

Advertisements

Responses

  1. You really make it seem so easy along with your presentation but I in finding this matter to be really one thing that I believe I’d by no means understand. It sort of feels too complicated and very huge for me. I’m taking a look ahead on your next post, I’ll attempt to get the dangle of it!

  2. Hello my friend! I want to say that this post is amazing, nice written and come with approximately all important infos. I would like to look extra posts like this .

  3. “Book Excerpt – HTML5 Attributes in MVC | Lyle’s Blog” Blinds For Windows honestly got me personally addicted on ur site! I personallywill certainly wind up being back again a whole lot more frequently. With thanks -Shane


What do you think?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: