Published: 10 Nov 2010
By: Xianzhong Zhu
Download Sample Code

In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.

Contents [hide]

The Experience ASP.NET MVC 3 Beta series

  • Part 1 In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.
  • Part 2 In addition to the introduction of a new view engine Razor, ASP.NET MVC 3 Beta has also introduced numerous new HtmlHelpers, such as Chart, Crypto, WebGrid, WebImage, WebMail, etc. This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.
  • Part 3 In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.
  • Part 4 In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.
  • Part 5 Starting from this article, let's explore some more advanced concepts and related utilizations associated with flexible Dependency Injection support introduced in ASP.NET MVC 3 Beta.
  • Part 6 In the last article, we've mainly discussed the new-styled DI support in ASP.NET MVC 3 Beta/RC in relation to the two new services - IControllerActivator and IViewPageActivator. Obviously, both of them are connected with controllers and views. In this article, however, we will shift our attention to the Model (generally called viewmodal in many blogs) related DI manipulations.
  • Part 7 Since ASP.NET MVC 1, CSRF (Cross Site Request Forgery) has been considered by introducing a set of anti-forgery helpers. In this article, we are to detail into CSRF related concepts and ASP.NET MVC's helper functions again CSRF.
  • Part 8 In this series of articles, we are going to explore as many as possible aspects of cache programming in the latest ASP.NET MVC 3 RC2 framework. And also, all the related samples have been tested against the latest ASP.NET MVC 3 RC 2.
  • Part 9 In the first part of this series, we've mainly explored Output Cache related issues. In this second part, however, we are going to delve into the general Data Cache topic.
  • Introduction

    ASP.NET MVC 3.0 Beta has made a fundamental alteration to its Ajax and client validation code base, which is totally based on jQuery and its validation plug-in. With this change, ASP.NET MVC framework can benefit from the power of the jQuery library, enhance the performance and make it much easier to use. For example, with the unobtrusive JavaScript enabled, ASP.NET MVC 3.0 Beta framework can generate HTML 5 data- prefix attributes, decouples the scripts from the view content (ASPX or Razor).

    In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.

    NOTE

    The development environments we'll utilize in the sample application are:

    1. Windows XP Professional (SP3);

    2. .NET 4.0;

    3. Visual Studio 2010;

    4. ASP.NET MVC 3 Beta (http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0abac7a3-b302-4644-bd43-febf300b2c51).

    Introducing Unobtrusive JavaScript

    According to Wikipedia, unobtrusive JavaScript is a general approach to the use of JavaScript in web pages. Though the term is not formally defined, its basic principles are generally around the following:

    • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
    • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
    • Progressive enhancement to support user agents that may not support advanced JavaScript functionality

    Advocates of Unobtrusive JavaScript see it as part of the larger Web standards movement; much as the demand for cross-browser compatibility has driven the increasing emphasis on standardized markup and style, the increasing demand for rich Internet applications is driving the movement toward better practices with the use of JavaScript. The concept of Unobtrusiveness in relation to JavaScript programming was coined in 2002 by Stuart Langridge in the article "Unobtrusive DHTML, and the power of unordered lists". In the article Langridge argues for a way to keep all JavaScript code, including event handlers, outside of the HTML.

    Scraps of samples

    Traditionally, JavaScript was often placed inline together with an HTML document's markup. For example, the following is a typical implementation of JavaScript form validation:

    Adherents to "Unobtrusive Javascript" argue that the purpose of markup is to describe a document's structure, not its programmatic behavior and that combining the two negatively impacts a site's maintainability for similar reasons that combining content and presentation does. They also argue that inline event handlers are harder to use and maintain, when one needs to set handlers for several events on a single element, when one wants to set the same event handler on several elements, or when one is using event delegation. Nor can they be used with custom events.

    The unobtrusive solution is to register the necessary event handlers programmatically, rather than inline. Rather than adding the onchange attribute explicitly as above, the relevant element(s) are simply identified, for example by class, id or some other means in the markup:

    A script that runs when the page is first loaded into the browser can look for the relevant element(s) and set them up accordingly.

    For example, using native JavaScript, HTML5 events and DOM Level 2 event listeners:

    The above example will not work in all browsers; some – particularly Internet Explorer (including version 8) – do not support DOM 2 event listeners. In real scenarios, developers often use libraries to abstract away browser inconsistencies and deficiencies. For example, the following script is specific to the jQuery JavaScript library:

    As it uses id, or other valid attributes and characteristics of the markup, this approach is consistent with modern standards-based markup practices.

    By default, ASP.NET MVC 3 Beta uses jQuery validation in an unobtrusive manner in order to perform client-side validation. To gain more clarity and sharper contrast, let's first retrospect the traditional client-side validation.

    Traditional Client-side Validation

    First of all, we should notice that the client-side validation system since ASP.NET MVC 2.0 has been decoupled from the server-side validation system through the utilization of JSON. Compared with the server-side validation, the client-side validation is a pretty knotty one (which requires a better understanding with JavaScript programming). In this article, we will mainly focus upon the latter.

    Set up Model

    Start up Visual Studio 2010, select the "ASP.NET MVC 3 Web Application" template, and then select the project template "Internet Application" to create a project named Mvc3UnobtrusiveDemo.

    For simplicity, we are going to create a very simple Model named ValidationModel, as shown below:

    Above, with the help of C# data annotations, we've established the validation attributes for each related property. ASP.NET MVC 2 has built-in support for data annotation validation attributes for doing validation on a server. For details on how data annotations work with ASP.NET MVC 2, check out Brad’s blog post.

    NOTE:

    Because users may have browser-side scripting disabled or intentionally try to send bad data to the server the server-side validation is a MUST HAVE. On the other hand, client-side validation has the benefit of giving the users quick feedback, as well as offloads some work from the server. In fact, the client-side validation is not a lone story because although the client-side validation system in MVC 3 Beta has been decoupled from the server-side one the former is still relevant to the latter. And, at the same time, we should clearly realize that to achieve the better client-side validation often requires you to be proficient in Javascript coding, especially as far as custom Ajax-based client-side validation is concerned.

    Let's next set up the necessary action method to invoke our interested view, inside which the client-side validation will be performed.

    Create the Action method

    Right click the folder Controllers in the sample project Mvc3UnobtrusiveDemo and select "Add| Controller..." to add a controller named ValidationController. Then, create a simple action named TraditionalValidation, as illustrated below.

    Above, we've built up a simple action TraditionalValidation with which to trigger the related view. Also, note the second action UnobtrusiveValidation will be used for test unobtrusive client-side validation later on.

    Create the view

    Now, right click the above action TraditionalValidation and from the shortcut menu select "Add View..." to create a new and strongly-typed view named TraditionalValidation, selecting the View engine as ASPX(C#). This view will serve two purposes: one is the traditional client-side validation; the other is unobtrusive jQuery-based client-side validation.

    Well, let's take a look at the first case - the traditional client-side validation. Below gives the main coding.

    First of all, we enabled the client-side validation support with the first line of code. Next, we turned off the unobtrusive JavaScript support. In this way, we will capture the same client-side markup output as ASP.NET MVC 2.0. And then, we set up a simple form with the strongly-typed class ValidationModel as the viewmodel.

    Now, let's save up all newly-created files and press Ctrl+F5 to launch the sample application. Then, enter the url http://localhost:yourportnumber/Validation/TraditionalValidation and hit the ENTER key. If everything goes well, you will see something like Figure 1 below.

    Figure 1: The traditional client-side validation in a MVC application

    The traditional client-side validation in a MVC application

    Till now, if you click "View |Source file" in your Internet Explorer, you will obtain the following client-side markup. For clarity, unimportant stuff has been omitted.

    Have you noticed the second part starting from //<![CDATA[ ? This is the well-known JSON blob through traditional client-side validation, which in some degree will affect the system performance.

    Starting from next section we are going to delve into the unobtrusive client validation shipped with ASP.NET MVC 3 Beta.

    Unobtrusive jQuery-based Client-side Validation

    Since version 2.0, ASP.NET MVC has been supporting both client- and server-side validation. In essence, the client-side validation in MVC 2 is a custom validation system written against ASP.NET Ajax.

    In this section, we're going to delve into ASP.NET MVC 3 Beta supported client-side validation. First, let's look at how to enable the MVC 3 Beta client-side validation.

    Enabling Unobtrusive Ajax-based JavaScript validation

    ASP.NET MVC 3 Beta provides us a single flag to turn on unobtrusive JavaScript mode, which enables both unobtrusive Ajax and unobtrusive client validation. Notice that, by default, unobtrusive JavaScript mode is turned off for backward compatibility with older projects. However, this flag is turned on in the default ASP.NET MVC 3 Beta project template. Additionally, to achieve the unobtrusive client-side validation, we also need to enable client-side validation (which remains off by default).

    In ASP.NET MVC 3 Beta, you can enable or disable client validation and unobtrusive JavaScript globally using static members of the HtmlHelper class, as in the following example:

    In reality, we can also enable or disable these features in the root Web.config file of the MVC application using the following settings:

    Note that using the preceding code means to turn these features on or off will behave contextually. If those lines of code are present in the Global.asax file, then it turns unobtrusive JavaScript and client validation on or off for the whole application. If they appear within the controller or view, though, it will turn the features on or off for the current action only.

    In addition to setting the flag, you will also need to include three script files:

    • jQuery (~/Scripts/jquery-1.4.1.js)
    • jQuery Validate (~/Scripts/jquery.validate.js)
    • the MVC plugin for unobtrusive client validation with jQuery Validate (~/Scripts/jquery.validate.unobtrusive.js).

    Next, let's look at the related example.

    The second sample

    Now, we right click the previous action UnobtrusiveValidation to create another view named UnobtrusiveValidation to make test upon the unobtrusive case. Note the view UnobtrusiveValidation.aspx has nearly the same markup as the first view TraditionalValidation.aspx, except for the following.

    Now, if you start up the sample project again and enter a new url "http://localhost:yourportnumber/Validation/ UnobtrusiveValidation" and hit the ENTER key, you will find out the following markup output: (some unimportant HTML removed)

    In the above case, with unobtrusive Ajax mode enabled in MVC 3, the HTML we generate looks drastically different. The biggest change is obviously that we don't emit the JSON blob any more. Instead, we've replaced the JSON with HTML 5-compatible attributes which describe the validators to be attached to the input fields. We've also attached some HTML attributes to the validation message spans so that they can be related to the input field they're attached to. Since the HTML attributes are all directly attached to the HTML elements they affect, we were also able to get rid of several cases of auto-generated IDs that were no longer necessary.

    Till now, there are still two things needed to be made clear. First, to start up the script support for the unobtrusive case we've leveraged a custom HTML helper named RegisterJS to be introduced in detail in the next section. Second, in the above samples we've only discussed the built-in client-side support but not touched upon the custom client-side case. For related details, I suggest you to read a good blog at http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx.

    In the next section, we'll shift our attention to the newly-introduced support for unobtrusive jQuery-base Ajax techniques in ASP.NET MVC 3 Beta.

    New Support for Unobtrusive jQuery-Based Ajax

    Ever since 1.0 ASP.NET MVC has supplied Ajax helper methods such as the following (each with several overloading forms):

    • Ajax.ActionLink
    • Ajax.RouteLink
    • Ajax.BeginForm
    • Ajax.BeginRouteForm

    In writing an ASP.NET MVC application that requires ASP.NET AJAX support we usually resort to the above four methods (and their variants).

    NOTE:

    In a typical ASP.NET MVC development, Ajax related techniques can be achieved through three kinds of solutions: the original Ajax mode, the jQuery mode, and the Ajax helper methods mode, each of which bears its own advantages and disadvantages. In this case, we are only interested in the second one.

    The above four methods all use JavaScript to invoke an action method on the server rather than using a full postback. It's worth noticing that in ASP.NET MVC 3 Beta all these functionalities have been updated to take advantage of jQuery in an unobtrusive means.

    Rather than emitting inline client scripts, these enhanced helper methods can separate the behavior from the markup by emitting HTML 5 attributes using the data-ajax prefix, so that the system performance gets enhanced and easier to use. To enable this, you should reference the following appropriate JavaScript files:

    • jquery-1.4.1.js
    • jquery.unobtrusive.ajax.js

    Note again this feature is enabled by default in the Web.config file in the ASP.NET MVC 3 new project templates, but is disabled by default for existing projects.

    Before turning to the interesting example application, let's first introduce a useful tool.

    A useful custom HTML helper

    In developing ASP.NET MVC application, I find it's difficult to manage the file path related to .js files. For example, if you use the following forms:

    or

    It sometimes results in some running-time error like "The symbol 'Sys' undefined..." especially when I publish my MVC applications through IIS. To find out a uniform solution to this, I surfed, through the Internet, a useful custom HTML helper at http://blog.wekeroad.com/blog/asp-net-mvc-script-registration-helper/. Note herein I used the initial content while in the later sample I revised it.

    It's an excellent tool! Isn't it? Well, to use the above custom HTML helper is pretty simple. In my master page, like Site.Master, at the topmost part, put the following:

    Then, in the <head/> part you can utilize the above custom helper like this:

    Here, we enabled the Ajax support (refer to the above code), since we are going to utilize the Ajax related stuffs.

    NOTE:

    For a detailed tutorial about writing custom HTML helpers, please refer to this url.

    In essence, the above method RouteLink resembles ActionLink; the method BeginRouteForm resembles BeginForm. For detailed related examples concerning the four methods, you can refer to this url in MSDN. And for this, in this article we'll mainly delve into Ajax.ActionLink and Ajax.BeginForm.

    With the above tools in place, we can turn to our true topic.

    Old version of Ajax.ActionLink

    As usual, to get a better understanding with the great change in MVC 3, let's first build an ASP.NET MVC 2 application and look at what happens.

    NOTE:

    The method Ajax.ActionLink and the next method Ajax.BeginForm related samples are both in a new MVC 2 sample project named MvcApplication3.

    Let's first look at the main view (ActionLinkTest.aspx) content:

    When start up this view, a url with text "test" is shown. Then, when you click it the action Hello in the controller Home will be triggered passing a string "A partical update happens here!" as the only parameter. With the last parameter of the method Ajax.ActionLink, we specify the output of this action will be populated into the HTML <div/> element with id being results.

    Next, let's take a quick look at the related action named Hello, as shown below:

    As indicated here, if the client-side request is of Ajax type, then a string beginning with "Hello" and ended with the passed string will be returned; or else, another simple string "non-ajax!" will be returned.

    Now, start up the sample application and navigate to the above view related url route, and you will find out the output source looking like the following:

    How about the thing with ASP.NET MVC 3 Beta? Let's continue our story.

    Current version of Ajax.ActionLink

    In our ASP.NET MVC 3 Beta sample project named Mvc3UnobtrusiveDemo, to stand out our interested topic, I purposefully put the reference to the revised custom HTML helper inside the view ActionLinkTest.aspx (the same name as above).

    Then, similarly, I put in the following content:

    First, for complete code of our revised version of the custom HTML helper, please see the attached source code (in file CustomHelperExtensions.cs under the folder CustomHelpers) with the article.

    With the necessary script files ready, the next thing worth noticing is enable the unobtrusive JavaScript support, like this:

    Of course, you can put the like thing in the web.config file (as covered previously). Here, still for emphasis, we utilized these two statements.

    Well now, let's look at the output source, looking like the following:

    Note here the previous intrusively emitted JavaScript statement has been replaced with some new attribute started with "data-ajax". In fact, if you put other more HTML elements (such as <label/>, <input/>, <span/>, etc.) in the above view you will find out some other new changes.

    About the other three methods - Ajax.RouteLink, Ajax.BeginForm and Ajax.BeginRouteForm

    Referring to the above sample, I think, you can easily construct the similar samples testing the other three Ajax related methods - Ajax.RouteLink, Ajax.BeginForm, and Ajax.BeginRouteForm.

    In fact, I've already provided one such sample. Refer to the file AjaxFormTest.aspx (concerning the Ajax.BeginForm method) in the downloadable project. But for brevity, I'm not going to delve into it any more.

    Summary

    In this article we've examined another aspect of the coming ASP.NET MVC 3 - the unobtrusive jQuery-based Ajax support, as well as unobtrusive client-side validation. Since these stuffs are not about a final MVC 3 release, something among them might change. And therefore, this is just for new learners' reference.

    The Experience ASP.NET MVC 3 Beta series

  • Part 1 In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.
  • Part 2 In addition to the introduction of a new view engine Razor, ASP.NET MVC 3 Beta has also introduced numerous new HtmlHelpers, such as Chart, Crypto, WebGrid, WebImage, WebMail, etc. This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.
  • Part 3 In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.
  • Part 4 In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.
  • Part 5 Starting from this article, let's explore some more advanced concepts and related utilizations associated with flexible Dependency Injection support introduced in ASP.NET MVC 3 Beta.
  • Part 6 In the last article, we've mainly discussed the new-styled DI support in ASP.NET MVC 3 Beta/RC in relation to the two new services - IControllerActivator and IViewPageActivator. Obviously, both of them are connected with controllers and views. In this article, however, we will shift our attention to the Model (generally called viewmodal in many blogs) related DI manipulations.
  • Part 7 Since ASP.NET MVC 1, CSRF (Cross Site Request Forgery) has been considered by introducing a set of anti-forgery helpers. In this article, we are to detail into CSRF related concepts and ASP.NET MVC's helper functions again CSRF.
  • Part 8 In this series of articles, we are going to explore as many as possible aspects of cache programming in the latest ASP.NET MVC 3 RC2 framework. And also, all the related samples have been tested against the latest ASP.NET MVC 3 RC 2.
  • Part 9 In the first part of this series, we've mainly explored Output Cache related issues. In this second part, however, we are going to delve into the general Data Cache topic.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Xianzhong Zhu

    I'm a college teacher and also a freelance developer and writer from WeiFang China, with more than fourteen years of experience in design, and development of various kinds of products and applications on Windows platform. My expertise is in Visual C++/Basic/C#, SQL Server 2000/2005/2008, PHP+MyS...

    This author has published 81 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.
    jQuery Mobile Pages
    Brian Mains explains how to create pages with the jQuery Mobile framework.
    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...

    You might also be interested in the following related blog posts


    Telerik Introduces Free Web Testing Framework for ASP.NET AJAX and Silverlight read more
    jQuery Intellisense in VS 2008 read more
    Will ASP.NET MVC be the main web UI platform for ASP.NET? read more
    Download AjaxPro Beta with jQuery Support read more
    Using ASP.NET for AJAX in SharePoint Sites: Tread Gently for Now read more
    Sinking My Teeth Into ASP.NET AJAX 1.0 Beta 2 read more
    ASP.NET AJAX 1.0 Beta 2 Release read more
    ComponentArt's Web.UI for ASP.NET AJAX read more
    Ajax.NET Professional 6.6.2.2 with new Converters read more
    Download latest Ajax.NET Professional 6.4.28.1 read more
    Top
     
     
     

    Please login to rate or to leave a comment.

    Free Agile Project Management Tool from Telerik
    TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.