Monday 19 March 2012

Manage Data in HTML5 Forms with Entity Framework

Following the example from the February 2012 issue, an ASP.NET MVC 4 view displays a feedback form for users to fill out. This feedback form contains various input types, including an input box, a drop-down list, a text area, a check box, and a submit button. Because of the display requirements and the inconsistency of data sources involved in creating HTML forms, ASP.NET MVC 4 models need some help.

This is where ViewModels come into play. ViewModels allow you to shape data before sending it to the view for display. Since their purpose is for shaping the UI, ViewModels are not typically candidates for updating; however, a ViewModel is often what returns with the HTTP POST Request back to the server, and it is what you access in the corresponding action method of a controller. For more information on managing ViewModels in ASP.NET, refer to the blog post, “Use ViewModels to manage data & organize code in ASP.NET MVC applications.”

Capture the HTTP POST Request Data in ASP.NET MVC 4

When a user clicks a submit button, the browser initiates an HTTP Request (or an HTTPS Request for a secure connection) and sends the data to the server for processing. This HTTP Request contains the form values the user entered, so when the request arrives on the server side, you can retrieve the form elements easily in ASP.NET MVC 4 by a process called model binding.

Model binding is the mapping of HTML form elements to a strongly typed object that usually resides in the model or in a ViewModel. During run time, ASP.NET identifies the incoming HTML form elements contained in the HTTP Request and then matches them to properties of that object. Since a foundational aspect of ASP.NET MVC 4 development is a technique called convention over configuration, model binding follows the MVC 4 convention of matching form fields to model properties by type and name, as denoted in the FeedbackViewModel argument illustrated in Figure 1.

Model binding as seen from the Visual Studio 2010 Watch window

Figure 1 Model binding as seen from the Visual Studio 2010 Watch window
Once you have an object representing the data you need for inserts, updates or deletes, you can use that object according to your application requirements. This means you can update directly from the controller in smaller Web sites. For any reasonably sized enterprise application, however, you’ll likely call service layers (e.g., business logic or data access layers).
Before heading off to perform CRUD (Create/Read/Update/Delete) operations, data validation is necessary.

Validation on the Client Side with jQuery Mobile

Client-side validation is important because it notifies valid, legitimate users about their responsibilities when filling out the form. Keep in mind that validating data on the client side isn’t true validation—those with malicious intent can bypass client validation. Despite this potential risk, client-side validation provides necessary instruction to users and a high degree of interactivity.

Client-side validation works in ASP.NET MVC 4 views because of two scripts that you include in a view or layout page, as shown in Figure 2, and it works on mobile browsers as well as desktops. The scripts help you implement a development technique called unobtrusive validation, meaning that the JavaScript code doesn’t intersperse itself into markup in views; it is kept separate from the content and the display.
The code in Figure 2 demonstrates the scripts necessary for unobtrusive validation, and you might notice that they are the popular jQuery validation scripts.

  1. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" 
  2.     type="text/javascript"></script>
  3. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" 
  4.     type="text/javascript"></script>

Figure 2 jQuery validation scripts in views

In ASP.NET MVC 4, Html helpers use a combination of data annotations plus the jQuery validation scripts to produce both the client-side and server-side validation needed for Web applications. When ASP.NET MVC 4 sees an Html helper in a view, it looks at its model to find and apply data annotations before rendering the corresponding fields. Figure 3 illustrates Html helpers and their output in the browser.

  1. // This code in the view
  2. @Html.TextBoxFor(model => model.Feedback.CustomerName)
  3. @Html.ValidationMessageFor(model => model.Feedback.CustomerName)
  4.  
  5. <!--Produces this as HTML output -->
  6. <input name="Feedback.CustomerName" 
  7.            class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-b" 
  8.            id="Feedback_CustomerName" 
  9.            type="text" 
  10.            data-val-required="The Who are you? field is required." 
  11.            data-val="true" 
  12.            value=""/>

Figure 3 Html helpers and the client-side validation they produce

The data-val-required and data-val attributes in Figure 3 shows the use of the new HTML5 data-* attributes. ASP.NET MVC 4 renders these attributes so that jQuery validation can use them in tandem with jQuery Mobile for mobile Web applications. The result is the validation you see in the browser shown in Figure 4.



Figure 4 jQuery does unobtrusive validation on the client

Upon passing client validation, the HTML form data travels to the server for processing. The action method of the controller happens in the server, and the annotations execute their validation there as well.

Validation on the Server Side with Data Annotations in ASP.MVC 4

Even if you have client-side validation, you still need to perform server-side validation. Without server-side validation, you can never be sure whether the data is accurate, has been tampered with or is malicious.
There is more than one way to perform validation on the server side. You can use data annotations to declaratively set constraints on your data model, or you can use custom server-side validation if your needs are more complex. The model code in Figure 5 shows the use of data annotations on the model, which provide client-side and server-side validation as well as some aesthetic touches to the field’s display name.

  1. public class FeedbackModel 
  2.   public int Id { get; set; } 
  3.   
  4.   [Display(Name = "Who are you?")] 
  5.   [Required()] 
  6.   public string CustomerName { get; set; } 
  7.   
  8.   [Display(Name = "Your feedback is about...")] 
  9.   [Required()] 
  10.   public int FeedbackType { get; set; } 
  11.   
  12.   [Display(Name = "Leave your message!")] 
  13.   [Required()] 
  14.   public string Message { get; set; } 
  15.   
  16.   [Display(Name = "Is this urgent?")] 
  17.   public bool IsUrgent { get; set; } 
  18. }

Figure 5 Model with data annotations

The System.ComponentModel.DataAnnotations namespace contains many ready-to-use annotations, including the following:
  • Required
  • Regular Expression
  • Range: Number, Date, and so on
  • Data Type
If you need complex validation, add a CustomAttribute attribute to a property and write your own code to validate it. Alternatively, you can create your own custom attribute by inheriting from any attribute class and applying your own logic.
Upon passing data validation, the actual database update can proceed.

Updating the Data Source with Entity Framework

A typical CRUD application contains similar code to Figure 6 that updates and saves the form data back to the database using Entity Framework. Notice that the code to update the database doesn’t execute unless the ModelState.IsValid property is equal to true. This safety code is included in case the user doesn‘t allow JavaScript to run on his or her browser and serves as a fallback for client-side validation.

  1. public class HomeController : Controller
  2. {
  3.   FeedbackContext context = new FeedbackContext();
  4.   [HttpPost()]
  5.   public ActionResult Results(FeedbackViewModel viewModel)
  6.   {
  7.       var model = viewModel.Feedback;
  8.       if (ModelState.IsValid)
  9.       {
  10.           context.FeedbackModel.Add(model);               
  11.           UpdateModel(model);
  12.           context.SaveChanges();           
  13.       }
  14.       return RedirectToAction("Index");
  15.   }

Figure 6 Entity Framework at work in the controller

Figure 6 shows the complete code to update a model. Even though a ViewModel is necessary for rendering the proper display view, updates go through the model, using the UpdateModel method.
The UpdateModel method is a controller method that accepts an entity in your model and updates it. These changes happen in the model, and Entity Framework doesn’t save them in the database until the code successfully calls the SaveChanges method of the DbContext object.

Updating HTML form data from mobile devices is as seamless and easy as it is when working with data in traditional Web applications. With new jQuery frameworks and tools such as jQuery UI, jQuery Mobile, plug-ins and extensions, you have many options for collecting and storing user data.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.