European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 4 Hosting - Amsterdam :: How to Create Mobile-Friendly HTML5 Forms with ASP.NET MVC 4

clock December 20, 2012 05:22 by author Scott

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.

 



European World-Class Windows and ASP.NET Web Hosting Leader - HostForLIFE.eu

clock December 18, 2012 07:11 by author Scott

Fantastic and Excellent Support has made HostForLife.eu the Windows and ASP.NET Hosting service leader in European region. HostForLife.eu delivers enterprise-level hosting services to businesses of all sizes and kinds in European region and around the world. HostForLife.eu started its business in 2006 and since then, they have grown to serve more than 10,000 customers in European region. HostForLife.eu integrates the industry's best technologies for each customer's specific need and delivers it as a service via the company's commitment to excellent support. HostForLife.eu core products include Shared Hosting, Reseller Hosting, Cloud Computing Service, SharePoint Hosting and Dedicated Server hosting.

HostForLife.eu service is No #1 Top Recommended Windows and ASP.NET Hosting Service in European continent. Their services is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and many top European countries. For more information, please refer to http://www.microsoft.com/web/hosting/HostingProvider/Details/953.

HostForLife.eu has a very strong commitment to introduce their Windows and ASP.NET hosting service to the worldwide market. HostForLife.eu starts to target market in United States, Middle East and Asia/Australia in 2010 and by the end of 2013, HostForLife.eu will be the one-stop Windows and ASP.NET Hosting Solution for every ASP.NET enthusiast and developer.

HostForLife.eu leverages the best-in-class connectivity and technology to innovate industry-leading, fully automated solutions that empower enterprises with complete access, control, security, and scalability. With this insightful strategy and our peerless technical execution, HostForLife.eu has created the truly virtual data center—and made traditional hosting and managed/unmanaged services obsolete.

HostForLIFE.eu currently operates data center located in Amsterdam (Netherlands), offering complete redundancy in power, HVAC, fire suppression, network connectivity, and security. With over 53,000 sq ft of raised floor between the two facilities, HostForLife has an offering to fit any need. The datacenter facility sits atop multiple power grids driven by TXU electric, with PowerWare UPS battery backup power and dual diesel generators onsite. Our HVAC systems are condenser units by Data Aire to provide redundancy in cooling coupled with nine managed backbone providers.

HostForLife.eu does operate a data center located in Washington D.C (United States) too and this data center is best fits to customers who are targeting US market. Starting on Jan 2013, HostForLife.eu will operate a new data centre facility located in Singapore (Asia).

With three data centers that are located in different region, HostForLife.eu commits to provide service to all the customers worldwide. They hope they can achieve the best Windows and ASP.NET Hosting Awards in the World by the end of 2013.

About HostForLIFE.eu

HostForLife.eu is Microsoft No #1 Recommended Windows and ASP.NET Hosting in European Continent. Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and many top European countries.

Our number one goal is constant uptime. Our data center uses cutting edge technology, processes, and equipment. We have one of the best up time reputations in the industry.

Our second goal is providing excellent customer service. Our technical management structure is headed by professionals who have been in the industry since its inception. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in