Click here to Skip to main content
15,860,859 members
Articles / Web Development / IIS

Introduction to HTML5 Development using VS 2010, HTML5, jQuery Mobile and ASP.NET MVC 4

Rate me:
Please Sign up or sign in to vote.
4.80/5 (3 votes)
16 Jan 2013CPOL7 min read 63K   39   3
This is an introduction to HTML5 development using VS2010, HTML5, jQuery Mobile and ASP.NET MVC 4

Article source: http://kishore1021.wordpress.com/2012/04/01/introduction-to-html5-development-using-vs-2010-html5-jquery-mobile-and-asp-net-mvc-4/

Mobile apps and HTML5 are two of the hottest technologies right now, and there’s plenty of overlap. Web apps run in mobile browsers and can also be re-packaged as native apps on the various mobile platforms. Browser adoption for HTML5 features is accelerating rapidly. Many of the modern browsers (Internet Explorer 10, Chrome, Safari, Firefox, and Opera) already support between 75% and 90% of the feature set and this number is increasing daily. With the wide range of platforms to support, combined with the sheer power of mobile browsers, HTML5 is the "Write once, run anywhere" (WORA) solution. Modern mobile devices consist of powerful browsers that support many new HTML5 capabilities, CSS3 and advanced JavaScript. To see what features your browser supports, check out sites like html5test.com, caniuse.com. jquerymobile.com and html5please.com

In this post, we will learn how to create mobile Web applications that take advantage of HTML5, jQuery Mobile and ASP.NET MVC 4, you can effectively target multiple platforms with a single code base. Any browser, including mobile Web browsers, can render the HTML pages created with these technologies. You’ll still need to consider dealing with different browsers, but overall, Web applications are much easier to develop and maintain than multiple native applications in different languages.

Let's get started with the latest tools for Microsoft Web development: HTML5, jQuery Mobile and ASP.NET MVC 4.

Tools Needed for Development (Download and Install)

  • VS 2010 SP1 is required. If you have not installed VS 2010 SP1, install it from here
  • Download and install MVC 4 for Visual Studio 2010 from here
  • Get all the tools you need to create mobile applications targeting Windows Phone 7 from here

See the Windows Phone getting started guide here. After we develop in MVC4, use the Windows Phone Emulator to test the page with something closer to an actual mobile device.

JQuery Mobile is also part of the MVC 4 Mobile Web Application template in Visual Studio 2010. With the MVC 4 template, you can develop mobile Web sites with a consistent look and feel by using prebuilt themes, navigation and widgets. Additional features include built-in accessibility, touch and an API, so you can easily customize your applications. Click here to see a comprehensive list of supported platforms.

Creating an HTML5 Application

To create a new application, Open VS 2010 , select New from the File menu, and then New Project. The New Project dialog box pops up as shown in figure 1. Name it as tag status.

The application displays the information related to a bar code tag. So we need a place holder to enter barcode tag number and a button to retrieve the description through the API. And then, another read only textblock to display its description.

image

Fig 1: New Project dialog box – ASP.NET MVC4 Web application

The Mobile Application template contains the necessary jQuery and jQuery Mobile scripts as well as other necessary markup, such as semantic elements and the data-* attributes.

Figure 2 shows the application in Windows Phone 7. As you can see, we have a textbox so that the user can enter a barcode tag number and click on submit. Then we display the description in the textbox below the button. For simplicity, when the user clicks on the submit button, I am displaying the information entered by the user in tag number as the description.

imageimage

Fig 2: HTML5 mobile application
Adding Model Class
  • In the Solution Explorer, expand the solution files
  • Right Click on Models –> Add –> Class. Name it as TagModels (TagModels.cs) and add the following code. Regardless of whether the target is mobile or desktop, HTML5 form elements map to a property of an entity in a model. 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.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;namespace TagStatus.Models
{
    public class TagModel
    {
        [Display(Name = "Enter Tag Number")]
        [Required(ErrorMessage = "The Tag Number field is required.")]
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

In the above model code, you can see the Data Annotations Display and Required. Before the form submission process sends the HTTP Request to the server, 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 3 shows the data annotation after the search button is clicked without entering data in the Windows Phone 7 Emulator.

image

Fig 3: Data Annotations in HTML5
Adding controller Class

The idea here is that the controller must pass the model to the view for rendering.

  • In the Solution Explorer, expand the solution files
  • Right Click on Controllers–> Add –> Controller. Name it as TagController(TagController.cs) and add the following code. The names are very important. You can see that the class is derived from Controller class. Here, we added two methods for Lookup() action.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TagStatus.Models;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Http;
using System.Dynamic;
using System.Data;
using System.Json;
namespace TagStatus.Controllers
{

public class TagController : Controller
{
//
// GET: /Tag/
public ActionResult Index()
{
    return View();
}

[AllowAnonymous]
public ActionResult Lookup()
{
    return View();
}

[AllowAnonymous]
[HttpPost]
public ActionResult Lookup(TagModel model)
{
    if (ModelState.IsValid)
    {
    // //string url = "https://myapicom/svc1/v2/tags?project=usax&format=JSON";
    model.Description = model.Name;
    // /* CallApi apiPOItems = new CallApi()
    // {
    // ApiUrl = ConfigurationManager.AppSettings["Url_PO_LineItems"].Replace("{PO_NUMBER}", PONumber),
    // Format = "xml",
    // PageSize = intPageSize.ToString(),
    // Page = mintCurPage.ToString(),
    // Filter = getFilterString(),
    // OrderBy = ((hdnPOLNSortOrder.Value != "") ? hdnPOLNSortOrder.Value : "poln_lineno asc")
    // };
    // ds = apiPOItems.RetrieveData(ref strErrorMsg, ref intRecordCount);*/
    // string strErrorMsg = "";
    // int intRecordCount = -1;
    // DataSet ds;
    // CallApi apiPOItems = new CallApi()
    // {

    // //ApiUrl = "https://myapicom/svc1/v2/tags/00-RIE-FF-03?project=usax",
    // ApiUrl = sApiUrl,
    // // Format = "xml",
    // Format = "",
    // PageSize = "10",
    // Page = "1",
    // Filter = "",
    // OrderBy = ""
    // };
    // CallApi.ConnectCallComplete = true;
    // // ds = apiPOItems.RetrieveData(ref strErrorMsg, ref intRecordCount);
    // string strjsonres = apiPOItems.RetrieveJSON();
    // JsonObject jsonObject = (JsonObject)JsonValue.Parse(strjsonres);
    // var strvar = JsonValue.Parse(strjsonres);
    // var t1 = strvar["tags"];
    // var t2 = t1["tags"];
    // var t3 = t2["tags_delivery_status"];
    // String strdeliverystatus = t3.ToString();
    // strdeliverystatus = strdeliverystatus.Replace("\"","");
    // strdeliverystatus = strdeliverystatus.Replace("\\u000a", "");
    // strdeliverystatus = "" + strdeliverystatus + "";
    // // var v = jsonObject["tags"];
    // //// JsonArray items = (JsonArray)jsonObject["tags"];
    // // var vv = v[1];
    // // JsonValue jsval;
    // // bool b = jsonObject.TryGetValue("tags_delivery_status", out jsval);
    // if (strErrorMsg != "")
    // {
    // // There was an ERROR
    // }
    // //model.Description = ds.Tables[2].Rows[0]["tags_description"].ToString();
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}
}
}
Adding View
  • In the Solution Explorer, expand the solution files.
  • Right Click on Views–> Add –> New Folder. Name it as Tag as shown in fig 4.
  • Right Click on Tag Folder –>Add New Item to create Lookup.cshtml as shown in figure 5.

image

Fig 4: Solution Explorer folder layout

image

Fig 5: Selecting a new View

Add the following code to the Lookup.cshtml:

C#
@model TagStatus.Models.TagModel
@{
    ViewBag.Title = "Tag Status Application";
}

<h2>Tag Status Lookup</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true) 
    //style="background-color: #C0C0C0"

<fieldset>
<legend></legend>
<div class="editor-label">
@Html.LabelFor(m => m.Name)
</div>
<div class="editor-field">
    @Html.TextBoxFor(Model => Model.Name)
    @Html.ValidationMessageFor(Model => Model.Name)
</div>
<p>
    <input type="submit" value="Search" />
</p>
<div class="editor-label">
    @Html.DisplayTextFor(m => m.Description)
</div>
</fieldset>
}

@*@using (Html.BeginForm())
{
    //style="background-color: #C0C0C0"

    <p>Enter tag number to get tag status:</p>
    @Html.TextBoxFor(m => m.Name)

    <input type="submit" value="Search" />

    @Html.DisplayTextFor(m => m.Description)
}
*@

The view is the one 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 (Lookup) in the controller with the name of the view, that is, Lookup.cshtml.

Inside the view, various ASP.NET MVC 4 HTML Helpers present components of the ViewModel by rendering HTML elements that best fit the data types they map to in the ViewModel.

Final Step (Global.asax)

To get the Tag status page displayed when the application is run, change the RegisterRoute and add the Tag Controller and the action Lookup as shown below in Global.asax file.

C#
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Tag", 
        action = "Lookup", id = UrlParameter.Optional }
        //defaults: new { controller = "Student", 
        action = "StudentInfo", id = UrlParameter.Optional }
        //defaults: new { controller = "Home", 
        action = "Index", id = UrlParameter.Optional }
    );
}

With the Model, View and Controller in place, let us execute the project.

Testing the HTML Form on the Windows Phone 7 Emulator

Running the app from Visual Studio through browser 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 2 . You can enter a tag number and submit the form. Submitting the form directs the browser to send the form information to the Tag controller because of the call to the HTML Helper, Html.BeginForm(). The BeginForm method directs the HTTP request to the TagController controller and then runs the Lookup action method when the submit button is pressed.

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 to the Lookup action method. The controller code lives in the TagController 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 Model.

You can immediately examine the modifications the jQuery Mobile library made by taking the following steps:

  1. Launch a Web page from within Visual Studio (F5/Ctrl).
  2. Open the browser’s developer tools to expose the runtime source (F12 in most browsers).
  3. Use the View Source command to expose the originally rendered source.

You can see the HTML returned to the client is different from our source.

Software development is shifting toward the mobile space. Businesses want to carve their niche in the mobile marketplace with native mobile applications and mobile Web sites – the two types of applications available for mobile devices. Creating native applications with native code means developing separate software that targets each platform of interest (e.g., one XAML app for Windows Phone 7 and one Objective-C app for iOS). Maintaining and supporting multiple code bases is challenging, in part because most software developer teams don’t have the resources to do so, especially across a large number of customers. Independent contractors often have to focus on only one or two platforms, limiting their prospects.

"The future belongs to those who see possibilities before they become obvious." — John Scully

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Astrani Technology Solutions
United States United States
Kishore Babu Gaddam is a Senior Technology Consultant, Technology Evangelist turned Technology Entrepreneur and a regular speaker at national conferences, regional code camps and local user groups with over 14 years of experience in software product development. His experience includes building & managing award-winning software development teams, managing customer relationships, marketing and launching new software products & services. Kishore launched his technology career almost 15 years ago with a Robotics software development startup and has served in multiple roles since including developer, innovation leader, consultant, technology executive and business owner.

A technology specialist in C++, C#, XAML and Azure, he successfully published two applications to Windows store http://bit.ly/WinStoreApp and http://bit.ly/FlagsApp.

Kishore is the author of the popular Microsoft Technologies blog at http://www.kishore1021.wordpress.com/ and his work on Portable Class Library project in Visual Studio 2012– .NET 4.5 was featured on Channel 9 at http://bit.ly/msdnchannel9. Kishore enjoys helping people understand technical concepts that may initially seem complex and perform lot of Research & Development on emerging technologies to help solve some of the toughest customer issues. Kishore spends a lot of time teaching and mentoring developers to learn new technologies and to be better developers. He is a speaker at various code camps around Washington DC area, mainly at Microsoft Technology Center for NOVA code camp (http://bit.ly/novacc12), CMAP Code Camp Fall 2012 (http://bit.ly/novacc12), etc. The majority of his software development experience has centered on Microsoft technologies including MFC, COM, COM+, WCF, WPF, winRT, HTML5, RestAPI and SQL Server. You can follow Kishore on Twitter at www.twitter.com/kishore1021. He can be reached on email at researcherkishore@outlook.com

Comments and Discussions

 
GeneralMy vote of 4 Pin
Christian Amado24-Aug-12 16:43
professionalChristian Amado24-Aug-12 16:43 
Good work!
GeneralBlog post Pin
Tim Corey24-Aug-12 2:03
professionalTim Corey24-Aug-12 2:03 
GeneralRe: Blog post Pin
kishore Gaddam24-Aug-12 3:29
kishore Gaddam24-Aug-12 3:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.