Mobilized Web Project Templates in Visual Studio 2010

The MVC 4 Mobile project template in Visual Studio 2010 contains all the files and references necessary to create a mobile-friendly Web site. When you create a new MVC 4 Mobile project, you’ll notice the familiar Models, Views and Controllers folders requisite for all MVC 4 projects (mobile or not) alongside new or modified scripts in the \Scripts folder. The \Scripts folder is where you’ll find the many jQuery files that serve as an API for building mobile-friendly Web sites, in particular, the jquery.mobile-1.0b2.js file for development and its minified partner, jquery.mobile-1.0b2.min.js, for deployment.

The \Content folder contains the location for style sheets, images and design-related files. Keep in mind that the jquery.mobile-1.0b2.css style sheet defines a look and feel that specifically targets multiple mobile platforms. (See http://jquerymobile.com/gbs/ for a list of supported mobile and tablet platforms.) Much like JavaScript files, there are two style sheets: a fat version for development and a minified version for production.

Data Sources for HTML5 Forms: MVC 4 Models and ViewModels

Regardless of whether the target is mobile or desktop, HTML5 form elements map to a property of an entity in a model or a ViewModel. Because models expose varied data and data types, their representation in the user interface requires varied visual elements, such as text boxes, drop-down lists, check boxes and buttons. You can see the full set of available controls or elements at the jQuery Mobile Web site’s Form Element Gallery.

Simple forms that contain only text inputs and buttons are not the norm. Most forms have several types of data. Because of this data variety, coding and maintenance will be easier if you use a ViewModel. ViewModels are a combination of one or more types that together shape data that goes to the view for consumption and rendering.

Let’s say you want to build a quick way for users of your Web site to provide feedback. You need to collect the user’s name, the type of feedback the user wants to leave, the comment itself, and the priority of the comment—that is, whether or not it’s urgent. Figure 1 shows how the FeedbackModel class definition captures these features in simple data structures such as strings, an int, and a Boolean.

public class FeedbackModel
{
    public string CustomerName { get; set; }
    public int FeedbackType { get; set; }
    public string Message { get; set; }
    public bool IsUrgent { get; set; }
}

Figure 1 Feedback Model

The FeedbackType property in Figure 1 is of type int, and it corresponds to the value the user selects at run time in the feedback type drop-down list defined in Figure 3.

Figure 2 contains the definition for the FeedbackViewModel, which is a combination of the FeedbackModel described in Figure 1 and the FeedbackType class (described in Figure 3).

public class FeedbackViewModel
{
    public FeedbackModel Feedback { get; set; }
    public FeedbackType FeedbackType { get; set; }        
    public FeedbackViewModel()
    {
        Feedback = new FeedbackModel();
        FeedbackType = new FeedbackType();
    }
}

Figure 2 Feedback ViewModel Containing the FeedbackModel and FeedbackType Properties

The use of the FeedbackType property highlights the purpose of ViewModels, which, as I mentioned earlier, is to shape disparate data sources or models together to form a single consumable source from the view, using strongly typed syntax.

While you can represent most of the data in a simple ViewModel as text boxes or check boxes, you also need to capture the type of feedback, which is a list of name-value pairs exposed in code as a more complex dictionary object. Figure 3 shows the FeedbackType class and the dictionary contained within it.

public class FeedbackType
{
    public static SelectList FeedbackSelectList
    {
        get { return new SelectList(FeedbackDictionary, "Value", "Key"); }
    }
    public static readonly IDictionary<string, int> 
         FeedbackDictionary = new Dictionary<string, int> 
    { 
        { "Select the type ...", 0 },
        { "Leave a compliment", 1 },
        { "Leave a complaint", 2 },
        { "Leave some SPAM", 3 },
        { "Other", 9 }
    };
}

Figure 3 FeedbackType Class, Including User Feedback Types

Now that the ViewModel is complete, the controller must pass it to the view for rendering. This straightforward code is in Figure 4 and is virtually identical to code that passes back a model.

public ActionResult Feedback()
{
    FeedbackViewModel model = new FeedbackViewModel();
    return View(model);
}

Figure 4 Controller Passing the ViewModel to the View

The next step in the process is setting up the view.

Creating HTML5 Mobile Forms in ASP.NET MVC 4 Views

You use the standard Add New Item command in Visual Studio 2010 to create feedback.cshtml, the view that will host your HTML5 form. ASP.NET MVC 4 favors a development technique named convention over configuration, and the convention is to match the name of the action method (Feedback) in the controller in Figure 4 with the name of the view, that is, feedback.cshtml. You can find the Add New Item command from the shortcut menu in Solution Explorer or the Project menu.

Inside the view, various ASP.NET MVC 4 Html Helpers present components of the FeedbackViewModel by rendering HTML elements that best fit the data types they map to in the ViewModel. For example, CustomerName renders as a standard single-line text box, while the Message property renders as a text area. FeedbackType renders as an HTML drop-down list so that the user can easily select an item rather than manually enter it. Figure 5 shows that there is no lack of Html Helpers to choose from for building forms.

@using (Html.BeginForm( "Results","Home")) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Leave some feedback!</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.CustomerName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Feedback.CustomerName)
            @Html.ValidationMessageFor(model => model.Feedback.CustomerName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.FeedbackType)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Feedback.FeedbackType, 
                 FeedbackType.FeedbackSelectList) 
            @Html.ValidationMessageFor(model => model.Feedback.FeedbackType)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.Message)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Feedback.Message)
            @Html.ValidationMessageFor(model => model.Feedback.Message)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Feedback.IsUrgent)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Feedback.IsUrgent)
            @Html.ValidationMessageFor(model => model.Feedback.IsUrgent)
        </div>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

Figure 5 Html Helpers

With the ViewModel, controller and view, the form is now ready to test in the browser.

Testing the HTML Form on the Windows Phone 7 Emulator

Running a browser from Visual Studio is the easiest way to test the form, but the look and feel doesn’t behave in a very mobile-like way. For viewing the output and testing the form, the Windows Phone 7 Emulator works perfectly.

The HTML5 form displays in the Windows Phone 7 Emulator, as shown in Figure 6. You can enter a name, select a type from the drop-down list, fill in the comments and submit the form. Without modifications to the default styling provided by jQuery Mobile style sheets, the overall HTML5 form looks like the image on the left side of Figure 6. After tapping on the drop-down, the list of items looks like the image on the right side of Figure 6. Tapping a list item to select it returns the user to the form.

Figure 6 Interacting with the Windows Phone 7 Emulator

Submitting the form directs the browser to send the form information to the Home controller because of the call to the Html Helper, Html.BeginForm( "Results","Home"). The BeginForm method directs the HTTP request to the HomeController controller and then runs the Results action method, as the arguments denote.

Before the form submission process sends the HTTP Request to the server, however, client-side validation needs to happen. Annotating the data model accomplishes this task nicely. In addition to validation, data annotations provide a way for the Html.Label and Html.LabelFor helpers to produce customized property labels. Figure 7 details the entire data model with attributes for both validation and aesthetic annotations, and Figure 8 illustrates their results in the Windows Phone 7 Emulator.

public class FeedbackModel
{
    [Display(Name = "Who are you?")]
    [Required()]
    public string CustomerName { get; set; }
    [Display(Name = "Your feedback is about...")]
    public int FeedbackType { get; set; }
    [Display(Name = "Leave your message!")]
    [Required()]
    public string Message { get; set; }
    [Display(Name = "Is this urgent?")]
    public bool IsUrgent { get; set; }
}

Figure 7 Complete Data Model with Annotations

Figure 8 Left: Data Annotation Validations; Right: Data Annotation Aesthetics

You can customize the error message of the Required attribute to make the user interface friendlier. There are also many more annotations available in the System.Data.DataAnnotations namespace. If you can’t find a data annotation that fits your validation, aesthetic or security needs, inheriting from the System.Attribute class and extending it gives you that flexibility.

From the Phone to the Server Through HTTP POST

Once the user taps the submit button on the phone—and assuming the form passes validation—an HTTP POST Request is initiated and the data travels to the controller and action method designated in the Html.BeginForm method (as was shown in Figure 5). The sample from Figure 9 shows the controller code that lives in the HomeController and processes the data that the HTTP Request sends. Because of the power of ASP.NET MVC 4 model binding, you can access the HTML form values with the same strongly typed object used to create the form – your ViewModel.

[HttpPost()]
public ActionResult Results(FeedbackViewModel model)
{
    // calls to code to update model, validation, LOB code, etc...
    return View(model);
}

Figure 9 Capturing the HTTP POST Data in the Controller

When capturing HTTP POST data, data annotations once again assist in the task, since action methods that have no attribute stating the type of HTTP verb default to HTTP GET. 

Conclusion

Creating shiny new forms for mobile devices as well as desktops has never been easier with the partnership between ASP.NET MVC 4, jQuery Mobile and HTML5.