<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Encosia &#187; AJAX</title>
	<atom:link href="http://encosia.com/category/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://encosia.com</link>
	<description>ASP.NET and AJAX code, ideas, and examples.</description>
	<lastBuildDate>Wed, 01 Sep 2010 15:51:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>ASMX ScriptService mistake &#8211; Invalid JSON primitive</title>
		<link>http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/</link>
		<comments>http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/#comments</comments>
		<pubDate>Tue, 01 Jun 2010 04:33:58 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASMX Mistakes and Misconceptions]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=998</guid>
		<description><![CDATA[One group of searches that consistently brings traffic here is variations on the error: Invalid JSON primitive. Unfortunately, the post that Google sends that traffic to doesn’t address the issue until somewhere within its 150+ comments. Today, the topic gets its own post. If you’ve worked with ASMX ScriptServices or Page Methods without ASP.NET AJAX&#8217;s [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/">ASMX ScriptService mistake &#8211; Invalid JSON primitive</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/' rel='bookmark' title='Permanent Link: ASMX and JSON &ndash; Common mistakes and misconceptions'>ASMX and JSON &ndash; Common mistakes and misconceptions</a></li>
<li><a href='http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/' rel='bookmark' title='Permanent Link: ASMX ScriptService mistakes: Installation and configuration'>ASMX ScriptService mistakes: Installation and configuration</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>One group of searches that consistently brings traffic here is variations on the error: <strong>Invalid JSON primitive</strong>. Unfortunately, the post that Google sends that traffic to doesn’t address the issue until somewhere within its 150+ comments.</p>
<p>Today, the topic gets its own post.</p>
<p>If you’ve worked with ASMX ScriptServices or Page Methods without ASP.NET AJAX&#8217;s client-side proxy (e.g. using jQuery or pure XMLHttpRequest code), you’ve may have seen this cryptic error yourself. Or, perhaps you’ve just arrived here due to seeing it for the first time.</p>
<p>Either way, you may be surprised to learn that <strong>the most common reason for this error is that you’ve lied to ASP.NET</strong> during your AJAX request.</p>
<h3>It all begins with the Content-Type</h3>
<p>HTTP’s <a href="http://www.w3.org/Protocols/rfc1341/4_Content-Type.html" rel="nofollow" target="_blank">Content-Type</a> header is a fundamental aspect of communication between browsers and servers, yet often remains hidden from us in day-to-day development. <strong>The Content-Type header allows an HTTP connection to describe the format of its contents</strong>, using <a href="http://en.wikipedia.org/wiki/Internet_media_type" rel="nofollow" target="_blank">Internet media types</a> (also known as MIME types). A few common ones that you&#8217;ve probably seen before are <em>text/html</em>, <em>image/png</em>, and the more topical <em>application/json</em>.</p>
<p>Without the flexible negotiation process content types provide, your users’ browsers and your version of IIS would have to both be “ASMX Compatible” and “JSON Compatible” in order for ScriptServices to function. What a nightmare that would be! The IE6 difficulties we face today would pale in comparison.</p>
<p>Further, Content-Type negotiation is part of what allows a single URL, such as WebService.asmx, to represent data in more than one format (e.g. XML and JSON in ASMX’s case).</p>
<p>The benefits of Content-Type negotiation are well worth a bit of occasional hassle.</p>
<h3>Okay, but why does that matter?</h3>
<p>When your browser sends a POST request, the W3C&#8217;s recommendation is that it should default to using a Content-Type of <em>application/x-www-form-urlencoded</em>. <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1" rel="nofollow" target="_blank">The HTML 4.01 spec describes that serialization scheme</a>:</p>
<blockquote>
<p>This is the default content type. Forms submitted with this content type must be encoded as follows:</p>
<ol>
<li>[Omitted for brevity; not relevant to this post.] </li>
<li>The control names/values are listed in the order they appear in the document. <strong>The name is separated from the value by &#8216;=&#8217; and name/value pairs are separated from each other by &#8216;&amp;&#8217;.</strong> </li>
</ol>
</blockquote>
<p>For an example of what that means, consider this simple form:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;form</span> <span style="color: #000066;">method</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;post&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;label&gt;</span></span>First Name<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/label&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;input</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;FirstName&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;Dave&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;FirstName&quot;</span> <span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;label&gt;</span></span>Last Name<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/label&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;input</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;LastName&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;Ward&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;LastName&quot;</span> <span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/form&gt;</span></span></pre></div></div>

<p>When the preceding form is submitted with URL encoded serialization, the request’s POST data will look like this:</p>
<p><img title="URLEncoded POST data" alt="Firebug screenshot showing the URLEncoded POST data" src="http://encosia.com/blog/wp-content/uploads/2010/05/url-encoded-post-data.png" width="492" height="172" /></p>
<p>That standardized serialization format allows a server-side backend like ASP.NET to decipher a form submission’s contents and give you access to each key/value pair. Regardless of what sort of browser submits a form to the server, the Content-Type facilitates a predictable conversion from POST data to server-side collection.</p>
<p>In other words, <strong>the Content-Type corresponds to a serialization scheme</strong>.</p>
<h3>What does that have to do with JSON Primitives?</h3>
<p>Understanding Content-Type negotiation and how it relates to serialization is important due to its role in coaxing JSON out of ASMX ScriptServices. Specifically, the fact that <a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/" target="_blank">you must set a Content-Type of application/json on the request</a><em></em> means <strong>you’re instructing ASP.NET to interpret your input parameters as JSON serialized data</strong>.</p>
<p>However, the W3C&#8217;s mandate of URL encoding by default means that most AJAX libraries default to that serialization scheme. Similarly, AJAX tutorials targeting endpoints other than ASMX ScriptServices (including even ASP.NET MVC examples) will describe sending URL encoded data to the server.</p>
<p>In other words, when you’re working with a client-side object like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Person <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> FirstName<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Dave'</span><span style="color: #339933;">,</span> 
               LastName<span style="color: #339933;">:</span>  <span style="color: #3366CC;">'Ward'</span> <span style="color: #009900;">&#125;</span></pre></div></div>

<p>The default serialization scheme makes it easy to inadvertently transmit that data to the server as a URL encoded string:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">FirstName<span style="color: #339933;">=</span>Dave<span style="color: #339933;">&amp;</span>LastName<span style="color: #339933;">=</span>Ward</pre></div></div>

<p>Again, remember that <a target="_blank" href="http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx">a Content-Type of <em>application/json</em> is a requirement when working with ASMX ScriptServices</a>. By setting that Content-Type on the request, you’ve committed to sending JSON serialized parameters, and a URL encoded string is far from valid JSON.</p>
<p>In fact, it’s <strong>invalid JSON</strong> (primitive?), hence the cryptic error message.</p>
<p>Instead of the URL encoded string above, you must be sure to send a JSON string:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'FirstName'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'Dave'</span><span style="color: #339933;">,</span><span style="color: #3366CC;">'LastName'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'Ward'</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>Whether you&#8217;re using XMLHttpRequest directly or a JavaScript library that abstracts the details, getting your request&#8217;s serialization wrong is the root of the invalid JSON primitive error. However, a more specific issue tends to be the leading cause of this happening.</p>
<h3>When good JavaScript libraries go bad</h3>
<p>The most common source of this error stems from a subtlety of using jQuery’s $.ajax() method to call ASMX ScriptServices. Cobbling together snippets of code from the documentation, platform agnostic tutorials, and even posts here on my site, it’s easy to end up with something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// WRONG!</span>
$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">'POST'</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'application/json'</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'json'</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">'WebService.asmx/Hello'</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> FirstName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Dave&quot;</span><span style="color: #339933;">,</span> LastName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Ward&quot;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Notice the JavaScript object literal being supplied to $.ajax()’s data parameter. That appears vaguely correct, but will result in the invalid JSON primitive error.</p>
<p>Why? <strong>jQuery serializes $.ajax()’s data parameter using the URL encoded scheme, regardless of what Content-Type is specified</strong>. Even though the contentType parameter clearly specifies JSON serialization, this URL encoded string is what jQuery will send to the server:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">FirstName<span style="color: #339933;">=</span>Dave<span style="color: #339933;">&amp;</span>LastName<span style="color: #339933;">=</span>Ward</pre></div></div>

<p>That obviously isn&#8217;t valid JSON!</p>
<p>The solution is as simple as two single-quotes:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// RIGHT</span>
$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">'POST'</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'application/json'</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'json'</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">'WebService.asmx/Hello'</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">'{ FirstName: &quot;Dave&quot;, LastName: &quot;Ward&quot; }'</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Did you spot the difference?</p>
<p>Instead of a JavaScript object literal, <strong>the data parameter is a JSON string now</strong>. <a href="http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/" target="_blank">The difference is subtle, but helpful to understand</a>. Since it’s a string, jQuery won’t attempt to perform any further transformation, and the JSON string will be unimpeded as it is passed to the ASMX ScriptService.</p>
<h3>It doesn’t have to be this way</h3>
<p>The problem is trivial once you’re aware of the underlying issue, but there’s not a great reason I can see why things need to be this way in the first place. Either half of this equation could easily provide a remedy.</p>
<p><strong>jQuery</strong> – I believe the most correct solution would be $.ajax() attempting to honor the serialization scheme indicated by its contentType parameter. In the case of <em>application/json</em>, fixing this could be easy as testing for JSON.stringify and using it if available.  That would work great, but also avoid adding any complexity/size to jQuery core.</p>
<p>That would leave it our responsibility to reference a copy of json2.js in older browsers, but that convention wouldn’t be much of a burden. <a href="http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/" target="_blank">We generally do that anyway when the client-side objects get complex</a>.</p>
<p><strong>Microsoft</strong> – It’s absolutely correct that the framework throws an error when you lie to it about what you’re sending. However, a bit of leniency could potentially save thousands of hours spent troubleshooting this problem (if my search traffic is any indication of its prevalence).</p>
<p>Is there any reason that the ScriptHandlerFactory can’t intelligently differentiate between between JSON and URL encoded inputs? If the first non-whitespace character of the request isn’t an opening curly brace, why not attempt to deserialize it as URL encoded before throwing an invalid JSON primitive error?</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/">ASMX ScriptService mistake &#8211; Invalid JSON primitive</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/' rel='bookmark' title='Permanent Link: ASMX and JSON &ndash; Common mistakes and misconceptions'>ASMX and JSON &ndash; Common mistakes and misconceptions</a></li>
<li><a href='http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/' rel='bookmark' title='Permanent Link: ASMX ScriptService mistakes: Installation and configuration'>ASMX ScriptService mistakes: Installation and configuration</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>ASMX ScriptService mistakes: Installation and configuration</title>
		<link>http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/</link>
		<comments>http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 03:29:07 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASMX Mistakes and Misconceptions]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=972</guid>
		<description><![CDATA[Continuing my series of posts about ASMX services and JSON, in this post I’m going to cover two common mistakes that plague the process of getting a project’s first ASMX ScriptService working: Installing System.Web.Extensions into the GAC and configuring your web.config. System.Web.Extensions (aka ASP.NET AJAX) The ability for ASMX services to return raw JSON is [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/">ASMX ScriptService mistakes: Installation and configuration</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/' rel='bookmark' title='Permanent Link: ASMX and JSON &ndash; Common mistakes and misconceptions'>ASMX and JSON &ndash; Common mistakes and misconceptions</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/' rel='bookmark' title='Permanent Link: A breaking change between versions of ASP.NET AJAX'>A breaking change between versions of ASP.NET AJAX</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Continuing <a href="http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/">my series of posts about ASMX services and JSON</a>, in this post I’m going to cover two common mistakes that plague the process of getting a project’s first ASMX ScriptService working: <strong>Installing System.Web.Extensions</strong> into the GAC and <strong>configuring your web.config</strong>.</p>
<h3>System.Web.Extensions (aka ASP.NET AJAX)</h3>
<p>The ability for ASMX services to return raw JSON is made possible by two key features originally added by the ASP.NET AJAX Extensions v1.0:</p>
<ul>
<li><strong>JavaScriptSerializer</strong> – <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(VS.100).aspx" target="_blank">The JavaScriptSerializer class</a> is the actual workhorse that translates back and forth between JSON strings and .NET CLR objects. Though less powerful than WCF’s DataContractJsonSerializer and third-party libraries like <a href="http://www.codeplex.com/Json" rel="nofollow" target="_blank">Json.NET</a>, JavaScriptSerializer is likely all you’ll ever need for simple AJAX callbacks. </li>
<li><strong>ScriptHandlerFactory</strong> – There are several more classes behind the scenes*, but the ScriptHandlerFactory is the tip of the iceberg that you&#8217;ll need to remember during configuration. Redirecting ASMX requests through this HttpHandler is what coordinates the pairing of ScriptService with JavaScriptSerializer to provide automatic JSON handling. </li>
</ul>
<p>Though both of these classes appear in the System.Web.Script namespace, they actually reside in ASP.NET AJAX&#8217;s System.Web.Extensions assembly. That has different implications depending on which version of ASP.NET your site targets:</p>
<ul>
<li><strong>1.x</strong> – No support for ScriptServices. A custom HttpHandler coupled with a third party library like <a href="http://james.newtonking.com/pages/json-net.aspx" target="_blank">Json.NET</a> is your best bet (if anyone has a good tutorial on doing this under 1.x, let me know so that I can link to it).</li>
<li><strong>2.0</strong> – ScriptServices are available in ASP.NET 2.0 with the installation of the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&amp;displaylang=en" rel="nofollow" target="_blank">ASP.NET AJAX Extensions v1.0</a>.
<ul>
<li>That means that <strong>the ASP.NET AJAX installer needs to be run on the server that hosts your site</strong>, not just on your local development machine.</li>
<li>For some of a ScriptService’s features to work in medium trust (i.e. shared hosting), the System.Web.Extensions assembly needs to be in your server’s global assembly cache (GAC). <a href="http://msmvps.com/blogs/luisabreu/archive/2007/11/22/stop-the-nonsense-don-t-put-the-system-web-extensions-dll-inside-your-bin-folder.aspx" target="_blank">Don’t waste your time trying to make it work in your site’s /bin directory</a>; insist that the extensions be properly installed on the server.</li>
</ul>
</li>
<li><strong>3.5+</strong> – As of .NET 3.5, System.Web.Extensions ships with the framework. No additional assemblies need be installed.</li>
</ul>
<p><em>* If you’re interested in the internals, I highly recommend downloading </em><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ef2c1acc-051a-4fe6-ad72-f3bed8623b43&amp;DisplayLang=en" rel="nofollow" target="_blank">the ASP.NET AJAX Extensions v1.0 source</a><em></em><em> and taking a look at ScriptHandlerFactory, RestHandlerFactory, and RestHandler. Though the classes have changed slightly since v1.0, they are still very similar.</em></p>
<h3>Rerouting the ASMX handler via web.config</h3>
<p>With the System.Web.Extensions assembly installed in the GAC, the remaining configuration step is an element in your site’s web.config. To take advantage of the ScriptService functionality, <strong>ASP.NET must be instructed to reroute ASMX requests through the ScriptHandlerFactory instead of ASP.NET’s standard ASMX handler</strong>.</p>
<p>This step is often unnecessary. The project templates in ASP.NET 3.5+ include all the necessary configuration elements, and ASP.NET 2.0 sites created with the “AJAX Enabled” templates are also pre-configured correctly.</p>
<p>However, if you find yourself unable to coax JSON out of an ASMX ScriptService, <strong>verifying your web.config is one of the best first steps in troubleshooting the issue</strong>. Whether due to a web.config generated by an older project template, accidental modification, or other issues, missing the httpHandlers web.config setting is a very common pitfall.</p>
<p>What should appear varies slightly depending on which version of ASP.NET your project targets. Regardless of your framework version, the config elements should be added to the &lt;httpHandlers&gt; section and are the only elements necessary. The <a href="http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx" rel="nofollow" target="_blank">variety of other config items required for the UpdatePanel and ScriptManager</a> aren’t crucial to the ScriptService functionality.</p>
<h4>ASP.NET 2.0 (with the ASP.NET AJAX Extensions installed)</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;system.web<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;httphandlers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;remove</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;*.asmx&quot;</span> <span style="color: #000066;">verb</span>=<span style="color: #ff0000;">&quot;*&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;*.asmx&quot;</span> <span style="color: #000066;">verb</span>=<span style="color: #ff0000;">&quot;*&quot;</span> <span style="color: #000066;">Culture</span>=neutral, <span style="color: #000066;">validate</span>=<span style="color: #ff0000;">&quot;false&quot;</span></span>
<span style="color: #009900;">           <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;System.Web.Script.Services.ScriptHandlerFactory, </span>
<span style="color: #009900;">                 System.Web.Extensions, Version=1.0.61025.0,</span>
<span style="color: #009900;">                 PublicKeyToken=31bf3856ad364e35&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/httphandlers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/system.web<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h4>ASP.NET 3.5</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;system.web<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;httphandlers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;remove</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;*.asmx&quot;</span> <span style="color: #000066;">verb</span>=<span style="color: #ff0000;">&quot;*&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;*.asmx&quot;</span> <span style="color: #000066;">verb</span>=<span style="color: #ff0000;">&quot;*&quot;</span> <span style="color: #000066;">Culture</span>=neutral, <span style="color: #000066;">validate</span>=<span style="color: #ff0000;">&quot;false&quot;</span></span>
<span style="color: #009900;">           <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;System.Web.Script.Services.ScriptHandlerFactory, </span>
<span style="color: #009900;">                 System.Web.Extensions, Version=3.5.0.0,</span>
<span style="color: #009900;">                 PublicKeyToken=31bf3856ad364e35&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/httphandlers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/system.web<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h4>ASP.NET 4</h4>
<p>Thankfully, <a href="http://www.asp.net/LEARN/whitepapers/aspnet4/default.aspx#_TOC1_1" rel="nofollow" target="_blank">ASP.NET 4 has taken steps to reverse the trend of ever-enlarging baseline web.config files</a>. By moving common configuration items such as the ScriptService’s HttpHandler to the default machine.config, each individual site need not include those configuration elements in their specific web.config files.</p>
<p>Unless you go out of your way to manually remove their HttpHandler, ASMX ScriptServices will work automatically in any ASP.NET 4 site.</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/">ASMX ScriptService mistakes: Installation and configuration</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/' rel='bookmark' title='Permanent Link: ASMX and JSON &ndash; Common mistakes and misconceptions'>ASMX and JSON &ndash; Common mistakes and misconceptions</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/' rel='bookmark' title='Permanent Link: A breaking change between versions of ASP.NET AJAX'>A breaking change between versions of ASP.NET AJAX</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASMX and JSON &#8211; Common mistakes and misconceptions</title>
		<link>http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/</link>
		<comments>http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 09:02:37 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASMX Mistakes and Misconceptions]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=971</guid>
		<description><![CDATA[While we were recording episode 5 of Mastering jQuery, I found myself running down a lengthy list of misconceptions and potential pitfalls when it comes to using ASMX services for AJAX callbacks. After years of fielding questions revolving around that topic, I suppose I’ve developed a decent handle on the issues most often encountered. To [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/">ASMX and JSON &ndash; Common mistakes and misconceptions</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
<li><a href='http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/' rel='bookmark' title='Permanent Link: A breaking change between versions of ASP.NET AJAX'>A breaking change between versions of ASP.NET AJAX</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>While we were recording <a href="http://tekpub.com/view/jquery/5" target="_blank">episode 5 of Mastering jQuery</a>, I found myself running down a lengthy list of misconceptions and potential pitfalls when it comes to using ASMX services for AJAX callbacks. After years of fielding questions revolving around that topic, I suppose I’ve developed a decent handle on the issues most often encountered.</p>
<p>To preemptively surface some of that commonly requested information, I’m going to publish a series of relatively short posts, each describing one mistake or misconception that I’ve seen come up frequently.</p>
<p>To get started, I want to cover one of the most fundamental of these misconceptions:  That ASMX services can&#8217;t return JSON.</p>
<h3>Misconception: ASMX services are limited to XML</h3>
<p>One of the most stubbornly persistent misconceptions about ASMX services is the rumor that they are limited to returning XML. With that notion mind, many developers understandably avoid them for client-side AJAX callbacks. When every byte counts, raw JSON is always preferable to the bloat of XML.</p>
<p>However, the introduction of <strong>ASP.NET AJAX removed that XML limitation</strong>.</p>
<p>In any ASP.NET 2.0+ AJAX enabled site, one of ASP.NET AJAX’s additions is something called the <strong>ScriptService</strong>. When a ScriptService is called in the correct manner, it automatically returns its result serialized as JSON instead of XML.</p>
<p>In fact, these <a href="http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/">ASMX ScriptServices even accept their parameters as JSON</a>.</p>
<h3>The ASP.NET AJAX “ScriptService”</h3>
<p>If you’ve created an ASMX service in the past few years, you’ve probably seen this blurb at the beginning of the default template:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// To allow this Web Service to be called from script, </span>
<span style="color: #008080; font-style: italic;">//   using ASP.NET AJAX, uncomment the following line. </span>
<span style="color: #008080; font-style: italic;">// [System.Web.Script.Services.ScriptService] </span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> WebService <span style="color: #008000;">:</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Web</span>.<span style="color: #0000FF;">Services</span></span>.<span style="color: #0000FF;">WebService</span> <span style="color: #000000;">&#123;</span></pre></div></div>

<p>Since it never explicitly mentions JSON <em>and</em> implies a tight coupling with ASP.NET AJAX, it’s easy to understand why the ScriptService’s true power sometimes goes unnoticed. Thankfully, that attribute does much more than simply expose ASP.NET AJAX specific functionality.</p>
<p>In fact, <strong>the ScriptService attribute enables all of an ASMX service’s methods to respond with raw JSON</strong> if they are requested correctly. For example, these ScriptServices can easily <a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/">send and receive JSON in conjunction with a third party library</a>, without a ScriptManager or MicrosoftAjax.js anywhere to be seen.</p>
<h3>Two simple requirements</h3>
<p>As I alluded to earlier, the one stipulation is that <strong>these ScriptServices only return JSON serialized results if they are requested properly</strong>. Otherwise, even a service marked with the attribute will return XML instead of JSON. I can only assume that’s part of the reason for the misconception that ASMX services cannot respond with JSON.</p>
<p>Scott Guthrie has a great post on <a href="http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx" target="_blank">the specific requirements for coercing JSON out of ScriptServices</a>. To summarize that, requests to the service methods must meet two requirements:</p>
<ul>
<li><strong>Content-Type</strong> – The HTTP request <em>must</em> declare a content-type of application/json. This informs the ScriptService that it will receive its parameters as JSON and that it should respond in kind.</li>
<li><strong>HTTP Method</strong> – By default, the HTTP request must be a POST request. It <em>is</em> possible to circumvent this requirement, but <a href="http://haacked.com/archive/2009/06/25/json-hijacking.aspx" target="_blank">it is advisable to stick with HTTP POST requests when dealing with JSON</a>.</li>
</ul>
<p>That’s it.</p>
<p>As long as those two requirements are satisfied, anything from low-level XMLHttpRequest code, to third-party libraries like jQuery, to ASP.NET AJAX itself can easily retrieve JSON serialized data from ASMX services.</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/">ASMX and JSON &ndash; Common mistakes and misconceptions</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
<li><a href='http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/' rel='bookmark' title='Permanent Link: A breaking change between versions of ASP.NET AJAX'>A breaking change between versions of ASP.NET AJAX</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>How you can force the Ajax Script Loader to use jQuery 1.4</title>
		<link>http://encosia.com/2010/01/15/how-you-can-force-the-ajax-script-loader-to-use-jquery-1-4/</link>
		<comments>http://encosia.com/2010/01/15/how-you-can-force-the-ajax-script-loader-to-use-jquery-1-4/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 05:24:57 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=962</guid>
		<description><![CDATA[If you’ve already begun using Microsoft’s new Ajax Script Loader with a CDN-hosted version of jQuery, today’s release of jQuery 1.4 may have left you wondering how to upgrade. Personally, I didn’t want to wait on a new version of Start.js, nor did I want to abandon the script loader now that I’ve become accustomed [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2010/01/15/how-you-can-force-the-ajax-script-loader-to-use-jquery-1-4/">How you can force the Ajax Script Loader to use jQuery 1.4</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
<li><a href='http://encosia.com/2007/08/16/updated-your-webconfig-but-sys-is-still-undefined/' rel='bookmark' title='Permanent Link: Updated your web.config, but Sys is still undefined?'>Updated your web.config, but Sys is still undefined?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>If you’ve already begun using Microsoft’s new <a href="http://www.asp.net/ajaxLibrary/Ajax%20Script%20Loader.ashx" target="_blank">Ajax Script Loader</a> with a CDN-hosted version of jQuery, today’s release of jQuery 1.4 may have left you wondering how to upgrade. Personally, I didn’t want to wait on a new version of Start.js, nor did I want to abandon the script loader now that I’ve become accustomed to its benefits.</p>
<p>No doubt, an upcoming ASP.NET Ajax Library iteration will update Start.js’ jQuery definition to reference jQuery 1.4.x. Regardless, <strong>knowing how to patch the script loader on your own terms is something that will be of recurring usefulness</strong>.</p>
<p>Luckily, <a href="http://weblogs.asp.net/bleroy/archive/2009/11/23/enabling-the-asp-net-ajax-script-loader-for-your-own-scripts.aspx" target="_blank">the script loader is open and extensible</a> enough that it’s possible to change which script versions are used. So, I want to briefly show you <strong>how the script loader defines JavaScript includes</strong> and how you can <strong>patch those definitions without modifying Start.js</strong> itself.</p>
<h3>Using the script loader to inject jQuery</h3>
<p>If you aren’t familiar with the script loader itself or with using it to asynchronously request jQuery, I recommend checking out <a href="http://www.asp.net/ajaxlibrary/Ajax%20Script%20Loader.ashx" target="_blank">its documentation and examples on the new ASP.NET Ajax Wiki</a>.</p>
<p>To use it most basically, simply include a reference to Start.js either locally or on the Microsoft CDN, and then use this JavaScript to instruct the script loader to inject jQuery into the page:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Instruct the script loader to request</span>
<span style="color: #006600; font-style: italic;">//  jQuery in the background.</span>
Sys.<span style="color: #660066;">require</span><span style="color: #009900;">&#40;</span>Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQuery</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// This callback runs later, after jQuery</span>
<span style="color: #006600; font-style: italic;">//  has been asynchronously loaded.</span>
Sys.<span style="color: #660066;">onReady</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Loaded jQuery &quot;</span> <span style="color: #339933;">+</span> jQuery.<span style="color: #660066;">fn</span>.<span style="color: #660066;">jquery</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Monitoring the request in Firebug illuminates what that Sys.require statement triggered in the background:</p>
<p><img style="border: #333 1px solid;" alt="Observing the script loader&#39;s default jQuery injection behavior" src="http://encosia.com/blog/wp-content/uploads/2010/01/script-loader-default.png" width="490" height="142" /></p>
<p>As you can see, the end result is pretty straightforward. The primary benefit of this asynchronous loading technique is that <strong>scripts loaded through the script loader are non-blocking and may be loaded in parallel</strong>. By contrast, JavaScript includes referenced through HTML script elements block all rendering and further requests until they are parsed and executed. <a href="http://www.stevesouders.com/blog/2009/04/27/loading-scripts-without-blocking/" target="_blank">The difference is often significant</a>.</p>
<p>Now, if only it were injecting jQuery 1.4 instead of 1.3.2.</p>
<h3>Understanding how Sys.scripts.jQuery is defined</h3>
<p>The Sys.scripts.jQuery parameter to the script loader is actually just a JavaScript object that defines a few parameters about the include. Here is how that is defined in Start.js (edited slightly for readability here):</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> path <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>window.<span style="color: #660066;">location</span>.<span style="color: #660066;">protocol</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">&quot;https&quot;</span> <span style="color: #339933;">?</span> <span style="color: #3366CC;">&quot;https&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;http&quot;</span><span style="color: #009900;">&#41;</span> 
           <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;://ajax.microsoft.com/ajax/&quot;</span><span style="color: #339933;">;</span>
&nbsp;
loader.<span style="color: #660066;">defineScripts</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>
 <span style="color: #009900;">&#123;</span> <span style="color: #000066;">name</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;jQuery&quot;</span><span style="color: #339933;">,</span>
   releaseUrl<span style="color: #339933;">:</span> path <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;jquery/jquery-1.3.2.min.js&quot;</span><span style="color: #339933;">,</span>
   debugUrl<span style="color: #339933;">:</span> path <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;jquery/jquery-1.3.2.js&quot;</span><span style="color: #339933;">,</span>
   isLoaded<span style="color: #339933;">:</span> <span style="color: #339933;">!!</span>window.<span style="color: #660066;">jQuery</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>If you’re using a local copy of Start.js, one option is to modify this jQuery script definition inside Start.js itself. However, I discourage that alternative. Not only would it require constant, manual maintenance after every new release, but it isn’t an option when using <a href="http://www.asp.net/ajaxLibrary/cdn.ashx" target="_blank">the Microsoft Ajax CDN’s</a> copy of Start.js.</p>
<h3>Defining a new target for it</h3>
<p>Another option is to <strong>simply modify the Sys.scripts.jQuery object itself</strong>. Letting Start.js initialize the definition with jQuery 1.3.2’s path doesn’t hurt anything as long as we redefine it before calling Sys.require.</p>
<p>Inspecting the Sys.scripts collection in Firebug reveals how straightforward that modification will be:</p>
<p><img style="border: #333 1px solid;" alt="Inspecting Sys.scripts.jQuery in Firebug" src="http://encosia.com/blog/wp-content/uploads/2010/01/Sys.scripts.jQuery-inspection.png" width="490" height="124" /></p>
<p>Thanks to to <a href="http://encosia.com/2009/09/21/updated-see-how-i-used-firebug-to-learn-jquery/" target="_blank">the power of interactively interrogating the object in Firebug</a>, it becomes clear that updating the releaseUrl and debugUrl properties of that object should be all that is necessary.</p>
<h3>Updating the example to use jQuery 1.4</h3>
<p>Because jQuery 1.4 isn’t available on the Microsoft CDN yet, I’m going to target <a href="http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/">Google’s AJAX Libraries CDN for jQuery</a> instead. Once Microsoft’s CDN is updated with jQuery 1.4.x, this approach will work for either CDN.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// These re-definitions must be executed after </span>
<span style="color: #006600; font-style: italic;">//  Start.js, but before Sys.require.</span>
<span style="color: #003366; font-weight: bold;">var</span> CDN <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;http://ajax.googleapis.com/ajax/libs&quot;</span><span style="color: #339933;">;</span>
&nbsp;
Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQuery</span>.<span style="color: #660066;">releaseUrl</span> <span style="color: #339933;">=</span> CDN <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/jquery/1.4.1/jquery.min.js&quot;</span><span style="color: #339933;">;</span>
Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQuery</span>.<span style="color: #660066;">debugUrl</span>   <span style="color: #339933;">=</span> CDN <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/jquery/1.4.1/jquery.js&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Instruct the script loader to request</span>
<span style="color: #006600; font-style: italic;">//  jQuery in the background.</span>
Sys.<span style="color: #660066;">require</span><span style="color: #009900;">&#40;</span>Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQuery</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// This callback runs later, after jQuery</span>
<span style="color: #006600; font-style: italic;">//  has been asynchronously loaded.</span>
Sys.<span style="color: #660066;">onReady</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  console.<span style="color: #660066;">log</span><span style="color: #3366CC;">&quot;Loaded jQuery &quot;</span> <span style="color: #339933;">+</span> jQuery.<span style="color: #660066;">fn</span>.<span style="color: #660066;">jquery</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>That’s all there is to it. Reviewing the requests in Firebug again, you can see that the same Sys.require statement is indeed now loading jQuery 1.4 from Google’s CDN:</p>
<p><img style="border: #333 1px solid;" alt="Observing the script loader&#39;s behavior after modifying Sys.scripts.jQuery" src="http://encosia.com/blog/wp-content/uploads/2010/01/script-loader-modified.png" width="490" /></p>
<h3>Bonus: jQuery Validate 1.6</h3>
<p>As I write this, Start.js’ definition for Sys.scripts.jQueryValidate is still targeting version 1.5.5 of the plugin, but <a href="http://www.asp.net/ajaxLibrary/CDNjQueryValidate16.ashx" target="_blank">1.6 is the current version</a>.</p>
<p>Using what&#8217;s been covered in this post, pointing the script loader at the newest version of jQuery Validate is no problem:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> MSCDN <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;http://ajax.microsoft.com/ajax&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> GoogCDN <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;http://ajax.googleapis.com/ajax/libs&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Please forgive my ugly formatting to make this fit. Do not try </span>
<span style="color: #006600; font-style: italic;">//  this at home (unless your editor is only 492px too).</span>
Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQuery</span>.<span style="color: #660066;">releaseUrl</span> <span style="color: #339933;">=</span> 
  GoogCDN <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/jquery/1.4.1/jquery.min.js&quot;</span><span style="color: #339933;">;</span>
Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQuery</span>.<span style="color: #660066;">debugUrl</span> <span style="color: #339933;">=</span> 
  GoogCDN <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/jquery/1.4.1/jquery.js&quot;</span><span style="color: #339933;">;</span>
&nbsp;
Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQueryValidate</span>.<span style="color: #660066;">releaseUrl</span> <span style="color: #339933;">=</span> 
  MSCDN <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/jQuery.Validate/1.6/jQuery.Validate.min.js&quot;</span><span style="color: #339933;">;</span>
Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQueryValidate</span>.<span style="color: #660066;">debugUrl</span> <span style="color: #339933;">=</span> 
  MSCDN <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;/jQuery.Validate/1.6/jQuery.Validate.js&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Instruct the script loader to request</span>
<span style="color: #006600; font-style: italic;">//  jQuery and jQuery Validate in the background.</span>
Sys.<span style="color: #660066;">require</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span>Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQuery</span><span style="color: #339933;">,</span> Sys.<span style="color: #660066;">scripts</span>.<span style="color: #660066;">jQueryValidate</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// This callback runs later, after both jQuery</span>
<span style="color: #006600; font-style: italic;">//  and jQuery Validate have been loaded.</span>
Sys.<span style="color: #660066;">onReady</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Loaded jQuery &quot;</span> <span style="color: #339933;">+</span> jQuery.<span style="color: #660066;">fn</span>.<span style="color: #660066;">jquery</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The jQuery Validate situation is a good example of why knowing how to update these script definitions yourself is worthwhile. Because the script loader was designed to be so flexible, there’s no need to wait on a new release of Start.js or give up its benefits.</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2010/01/15/how-you-can-force-the-ajax-script-loader-to-use-jquery-1-4/">How you can force the Ajax Script Loader to use jQuery 1.4</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
<li><a href='http://encosia.com/2007/08/16/updated-your-webconfig-but-sys-is-still-undefined/' rel='bookmark' title='Permanent Link: Updated your web.config, but Sys is still undefined?'>Updated your web.config, but Sys is still undefined?</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2010/01/15/how-you-can-force-the-ajax-script-loader-to-use-jquery-1-4/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Mastering jQuery now available at TekPub</title>
		<link>http://encosia.com/2009/12/16/mastering-jquery-now-available-at-tekpub/</link>
		<comments>http://encosia.com/2009/12/16/mastering-jquery-now-available-at-tekpub/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 14:52:42 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=951</guid>
		<description><![CDATA[If you haven’t been following the progress of Rob Conery and James Avery’s new venture, TekPub, you’ve been missing out on some great instructional videos. I especially like that they trend slightly Alt.NET, giving you more balanced information than is sometimes available from “official” .NET screencasts. For the past few weeks, I’ve been working with [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/12/16/mastering-jquery-now-available-at-tekpub/">Mastering jQuery now available at TekPub</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2008/10/10/altnet-podcast-jquery-in-aspnet/' rel='bookmark' title='Permanent Link: Alt.NET Podcast &ndash; jQuery in ASP.NET'>Alt.NET Podcast &ndash; jQuery in ASP.NET</a></li>
<li><a href='http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/' rel='bookmark' title='Permanent Link: Emulate ASP.NET validation groups with jQuery validation'>Emulate ASP.NET validation groups with jQuery validation</a></li>
<li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://tekpub.com/view/jquery/1?ref=encosia" target="_blank"><img border="0" alt="Mastering jQuery" src="http://encosia.com/blog/wp-content/uploads/2009/12/tekpub-mastering-jquery.jpg" width="492" height="242" /></a></p>
<p>If you haven’t been following the progress of Rob Conery and James Avery’s new venture, <a href="http://tekpub.com" target="_blank">TekPub</a>, you’ve been missing out on some great instructional videos. I especially like that they trend slightly Alt.NET, giving you more balanced information than is sometimes available from “official” .NET screencasts.</p>
<p>For the past few weeks, I’ve been working with James to record a series of episodes for TekPub myself: <strong>Mastering jQuery</strong>.</p>
<blockquote><p>Mastering jQuery walks through the basics of using jQuery, the revolutionary JavaScript framework that makes writing client-side code fun and easy, and then dives into the details of writing AJAX enabled ASP.NET MVC and ASP.NET Web Forms applications. We will also cover popular plugins and extending jQuery in future episodes.</p></blockquote>
<p>Today, the first video in that series is available: <a href="http://tekpub.com/view/jquery/1?ref=encosia" target="_blank">Getting Started with jQuery</a>.</p>
<blockquote><p>In this episode we cover the basics of getting started with jQuery. We start with a basic HTML page and show how to include jQuery, how to write your first code, and explain all of the moving pieces and how they work.</p></blockquote>
<p>If you’ve been following my site and working with jQuery already, the first episode may sound elementary, but there’s going to be something for everyone before the series is finished. By the third episode, we’re already into topics like making <strong>AJAX calls to MVC controller actions</strong> and <strong>progressively enhancing an entry form</strong> with the jQuery form plugin.</p>
<p>I hope you&#8217;ll head over to TekPub, and <a href="http://tekpub.com/view/jquery/1?ref=encosia" target="_blank">have a look for yourself</a>.</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/12/16/mastering-jquery-now-available-at-tekpub/">Mastering jQuery now available at TekPub</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2008/10/10/altnet-podcast-jquery-in-aspnet/' rel='bookmark' title='Permanent Link: Alt.NET Podcast &ndash; jQuery in ASP.NET'>Alt.NET Podcast &ndash; jQuery in ASP.NET</a></li>
<li><a href='http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/' rel='bookmark' title='Permanent Link: Emulate ASP.NET validation groups with jQuery validation'>Emulate ASP.NET validation groups with jQuery validation</a></li>
<li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/12/16/mastering-jquery-now-available-at-tekpub/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Emulate ASP.NET validation groups with jQuery validation</title>
		<link>http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/</link>
		<comments>http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 17:51:37 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=948</guid>
		<description><![CDATA[In my most recent post, I demonstrated a workaround to allow using the jQuery validation plugin with WebForms pages. The basic idea was to trigger validation only on submissions that occurred within a single logical form, instead of catching submissions anywhere on WebForms’ all-encompassing physical form. This approach worked fine for a single logical form, [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/">Emulate ASP.NET validation groups with jQuery validation</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/' rel='bookmark' title='Permanent Link: Using jQuery validation with ASP.NET WebForms'>Using jQuery validation with ASP.NET WebForms</a></li>
<li><a href='http://encosia.com/2008/10/11/using-jquery-to-display-a-modal-updatepanel-confirmation/' rel='bookmark' title='Permanent Link: Using jQuery to display a modal UpdatePanel confirmation'>Using jQuery to display a modal UpdatePanel confirmation</a></li>
<li><a href='http://encosia.com/2007/11/15/exploring-one-of-ms-ajaxs-often-overlooked-features/' rel='bookmark' title='Permanent Link: Exploring one of MS AJAX&#8217;s often overlooked features.'>Exploring one of MS AJAX&#8217;s often overlooked features.</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>In my most recent post, I demonstrated a workaround to allow <a href="http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/" target="_blank">using the jQuery validation plugin with WebForms pages</a>. The basic idea was to trigger validation only on submissions that occurred within a single logical form, instead of catching submissions anywhere on WebForms’ all-encompassing physical form.</p>
<p>This approach worked fine for a single logical form, but wasn&#8217;t robust enough when handling validation for multiple logical forms on a single page. Additionally, it did not properly handle the enter key, allowing users to (perhaps accidentally) slip past validation if they simply hit the enter key within a TextBox.</p>
<p>In this post, we will continue by refining the solution from last time. So, if you haven’t read the previous post, familiarize yourself with it first. Specifically, this post will cover how to <strong>implement an analogue of WebForms’ ValidationGroup</strong>, use that to <strong>independently validate multiple form regions</strong>, <strong>handle the enter key</strong>, and <strong>refactor the final solution</strong> to minimize duplicated code.</p>
<h3>ValidationGroups</h3>
<p>In WebForms, we have the concept of a <strong><a href="http://msdn.microsoft.com/en-us/library/ms227424.aspx" rel="nofollow" target="_blank">ValidationGroup</a></strong> to mitigate the issues that come with wrapping the entire page in a single form element. Whether right or wrong in principle, this scheme does a pretty good job of keeping the ASP.NET Validation controls from getting their wires crossed on complex forms.</p>
<p>However, using ASP.NET’s ValidationGroups requires that you use the WebForms validation controls, which generates quite a bit of cruft in your markup and injects two additional script references on your page.</p>
<p><img style="border: 1px solid #000;" alt="An example of some of the client-side code the ASP.NET Validators generates" src="http://encosia.com/blog/wp-content/uploads/2009/11/WebForms-validator-output.png" width="490" height="111" /></p>
<p>If you’re like me, trying to trend away from client-heavy WebForms pages <strong>these side-effects are prohibitive</strong>.</p>
<h3>Emulating Validation Groups</h3>
<p>Though its implementation renders a bit messy on the client-side, the WebForms paradigm of a ValidationGroup is exactly what we need for segregating our physical form element into logical forms. In fact, I’m going to use the same nomenclature in this example (ValidationGroup and CausesValidation).</p>
<p>Using CSS classes as flags is a great way to emulate that concept in plain (X)HTML markup. Especially when using jQuery, CSS “flags” are a great way to tag elements with arbitrary attributes, that are easy to find with simple DOM selectors later. Taking the form shown in my previous post and tagging its fieldsets with a validationGroup class, we end up with this markup:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;fieldset</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;validationGroup&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;legend&gt;</span></span>Returning customer?  Login here<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/legend&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #060; font-style: italic;">&lt;!-- Username and Password labels and inputs here --&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/fieldset&gt;</span></span></pre></div></div>

<p>Not a very large change, but it allows us to keep these logical forms separate, both when performing validation and when initially setting up their validation triggers.</p>
<h3>Creating a CausesValidation counterpart</h3>
<p>ValidationGroups may control the organization of logical forms, but it’s the controls marked with the CausesValidation property that drive validation of those forms. In similar fashion, we need a way to indicate which elements should trigger our own emulation of WebForms’ grouped validation.</p>
<p>Sticking with the same naming scheme and CSS flagging technique, it makes sense to tag our Button controls with a .causesValidation class:</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;">&lt;fieldset class=&quot;validationGroup&quot;&gt;
  &lt;legend&gt;Returning customer?  Login here&lt;/legend&gt;
&nbsp;
  <span style="color: #060; font-style: italic;">&lt;!-- Username and Password labels and inputs here --&gt;</span>
&nbsp;
  &lt;asp:Button runat=&quot;server&quot; ID=&quot;Login&quot; Text=&quot;Login&quot; 
              CssClass=&quot;causesValidation&quot; /&gt;
&lt;/fieldset&gt;</pre></div></div>

<p>Now we just need to wire up functionality to make those causesValidation flags actually do something.</p>
<h3>Acting on the validationGroup flag</h3>
<p>With the markup modified to allow selective targeting of the validation groups, the next step is implementing validation functionality that leverages that targeting. Using jQuery’s powerful CSS-based selectors, that isn’t difficult:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#form1&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">validate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> onsubmit<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Search for controls marked with the causesValidation flag </span>
  <span style="color: #006600; font-style: italic;">//  that are contained anywhere within elements marked as </span>
  <span style="color: #006600; font-style: italic;">//  validationGroups, and wire their click event up.</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.validationGroup .causesValidation'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>evt<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// Ascend from the button that triggered this click event </span>
    <span style="color: #006600; font-style: italic;">//  until we find a container element flagged with </span>
    <span style="color: #006600; font-style: italic;">//  .validationGroup and store a reference to that element.</span>
    <span style="color: #003366; font-weight: bold;">var</span> $group <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">parents</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.validationGroup'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">var</span> isValid <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// Descending from that .validationGroup element, find any input</span>
    <span style="color: #006600; font-style: italic;">//  elements within it, iterate over them, and run validation on </span>
    <span style="color: #006600; font-style: italic;">//  each of them.</span>
    $group.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">':input'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">valid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        isValid <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>isValid<span style="color: #009900;">&#41;</span>
      evt.<span style="color: #660066;">preventDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><em>Note: For more explanation of any uncommented code above, be sure to see <a href="http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/" target="_blank">the previous post in this series</a>. Those parts are explained in detail there.</em></p>
<p>This sets up a click event handler on any element flagged with the causesValidation class; the two Button controls in our case. When those raise click events, we start at the triggering element and use <a href="http://docs.jquery.com/Traversing/parents#expr" target="_blank">the parents() traversal method</a> to search upward for the nearest parent flagged as a validationGroup.</p>
<p>In this example, that will find a reference to the fieldset which contains the Button control that triggers the click event (e.g. if the user clicks the Login Button, then $group will store a reference to the first fieldset element).</p>
<p>With that reference to the the logical form requiring validation, <a href="http://docs.jquery.com/Traversing/find#expr" target="_blank">jQuery’s find() traversal method</a> allows us to select a set of all the input elements within just that region of the page. Note that this will also include the Button control that triggered the event, but since the valid() method returns <em>true</em> for elements that don’t have validation rules configured, this doesn’t cause a problem.</p>
<p>From there, it’s straightforward to iterate over the appropriate input elements and validate each independently, using <a href="http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/" target="_blank">the valid() trick covered in the last post</a>.</p>
<h3>Handling the enter key</h3>
<p>At this point, everything works pretty well, so long as the user <em>clicks</em> on the Button controls to submit the logical forms. Unfortunately, things fall apart if the user triggers form submission by pressing enter in one of the form fields.</p>
<p>One way to fix that would be to handle the form’s onsubmit event, determine if an element flagged with the causesValidation class triggered the submission, and then run through our validation first. That’s perfectly valid, but <strong>I avoid that because it tends to clash with other functionality that handles the event</strong>; <a href="http://jquery.malsup.com/form/" target="_blank">the jQuery form plugin</a> for example.</p>
<p>The alternative that I prefer is to handle a validated field’s onkeydown event. That way, if the element does need to trigger validation, it can do so early, and get out of the way quickly otherwise.</p>
<p>Using jQuery’s cross-browser normalized event object, testing for the enter key is not difficult at all. When handling keyboard related events, one property of that object is <strong>keyCode</strong>. This property will contain the ASCII character code of the key which triggered the event. In the case of the enter key, that keyCode is <strong>13</strong>.</p>
<p>That in mind, this is a first iteration of adding enter key handling to our existing validation code:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Select any input[type=text] elements within a validation group</span>
<span style="color: #006600; font-style: italic;">//  and attach keydown handlers to all of them.</span>
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.validationGroup :text'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">keydown</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>evt<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Only execute validation if the key pressed was enter.</span>
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>evt.<span style="color: #660066;">keyCode</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">13</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// Validation code goes here.</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Whether the form is submitted by clicking a button or hitting the enter key within one of our validation groups’ text fields, the appropriate inputs will be validated, error messages displayed if necessary, and <strong>submission will only continue if the form is valid</strong>.</p>
<h3>Refactoring to eliminate duplication</h3>
<p>After adding the keydown handler, everything works great, but it’s no good to have that validation code duplicated for both the click and keydown handlers. By passing around a reference to the jQuery event object, we can reuse the same validation code for both event types and make the code much more concise:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Initialize validation on the entire ASP.NET form.</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#form1&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">validate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// This prevents validation from running on every</span>
    <span style="color: #006600; font-style: italic;">//  form submission by default.</span>
    onsubmit<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Search for controls marked with the causesValidation flag </span>
  <span style="color: #006600; font-style: italic;">//  that are contained anywhere within elements marked as </span>
  <span style="color: #006600; font-style: italic;">//  validationGroups, and wire their click event up.</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.validationGroup .causesValidation'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span>ValidateAndSubmit<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Select any input[type=text] elements within a validation group</span>
  <span style="color: #006600; font-style: italic;">//  and attach keydown handlers to all of them.</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.validationGroup :text'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">keydown</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>evt<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// Only execute validation if the key pressed was enter.</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>evt.<span style="color: #660066;">keyCode</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">13</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      ValidateAndSubmit<span style="color: #009900;">&#40;</span>evt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> ValidateAndSubmit<span style="color: #009900;">&#40;</span>evt<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Ascend from the button that triggered this click event </span>
  <span style="color: #006600; font-style: italic;">//  until we find a container element flagged with </span>
  <span style="color: #006600; font-style: italic;">//  .validationGroup and store a reference to that element.</span>
  <span style="color: #003366; font-weight: bold;">var</span> $group <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span>evt.<span style="color: #660066;">currentTarget</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">parents</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.validationGroup'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">var</span> isValid <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Descending from that .validationGroup element, find any input</span>
  <span style="color: #006600; font-style: italic;">//  elements within it, iterate over them, and run validation on </span>
  <span style="color: #006600; font-style: italic;">//  each of them.</span>
  $group.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">':input'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">valid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      isValid <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// If any fields failed validation, prevent the button's click </span>
  <span style="color: #006600; font-style: italic;">//  event from triggering form submission.</span>
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>isValid<span style="color: #009900;">&#41;</span>
    evt.<span style="color: #660066;">preventDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>First, the validation code is refactored into a separate function: <strong>Validate</strong>.</p>
<p>Since it needs the ability to conditionally call preventDefault in order to stop form submission, the function accepts the event handlers’ jQuery event object as a parameter.</p>
<p>In fact, because $(this) is a reasonable place to begin the parents() traversal for either event that may call the method, very little refactoring is necessary.</p>
<p>The one thing that may seem strange is that the Validate function is being passed as a click handler without any parameters. <strong>The reason that this works is because the Validate function is defined with the same signature that jQuery expects</strong>. Because of that alignment, Validate will automatically be provided with the same event object that we’ve been using in anonymous callback functions thus far.</p>
<h3>Calculated readability</h3>
<p>Note that I attached keydown handlers to <em>all</em> of the text inputs within a validation group, <strong>regardless of whether or not they are actually validated fields</strong>. Similarly, you may have noticed that the click handler finds every input element within its validation group, even if those inputs aren’t marked for validation. This may seem like an oversight, but it’s an intended readability compromise.</p>
<p>You <em>could</em> modify the selector to be more precise, selecting only fields flagged with validation classes (e.g. <em>required</em>, <em>email</em>, <em>number</em>, etc). However, this gets messy when you consider <a href="http://docs.jquery.com/Plugins/Validation#List_of_built-in_Validation_methods" rel="nofollow" target="_blank">the wide variety of classes that are valid for tagging elements with jQuery validation functionality</a>.</p>
<p>Rather than be precisely specific, I rely on the fact that <strong>jQuery validation’s valid() method returns <em>true</em> for elements which are not configured for validation</strong>. So, even if we do end up checking the validation status of a few irrelevant input fields, it won’t adversely impact the outcome of the validation process.</p>
<p>There are performance penalties to performing validation on these unnecessary elements, but it is negligible for a reasonably sized form. The ancillary inputs would have to number in the thousands before the penalty were noticeable, at which no one will probably ever successfully complete it anyway!</p>
<h3>Conclusion</h3>
<p>There are even more enhancements to be had, but I think this brings the solution to a point that it’s useful. With multiple logical forms handled and the perennially pesky enter key tamed, the majority of use cases should be covered.</p>
<p>The most troublesome issue still remaining is that <strong>care should be taken to avoid nesting container elements with the validationGroup class on them</strong>. Otherwise, the Validate() function will search “too high” and possibly hinge validation on input fields that are not intended. It’s an edge case (fixable if necessary), but something to keep in mind.</p>
<p>Another edge case is that, unlike the ASP.NET Validators, <strong>these validation groups can’t overlap</strong>. For my own use, this has never been an issue. I’m curious if that’s a real-world problem for any of you.</p>
<p>Finally, an entirely different approach well worth considering is <a href="http://john.rummell.info/john/blog/" target="_blank">John Rummell</a>’s <a href="http://xvalwebforms.codeplex.com/" rel="nofollow" target="_blank">xVal for Webforms</a>. Using Data Annotations to specify validation rules is gaining a lot of popularity, so it’s worth investigating options like this one. At the minimum, it will help you be more familiar with how validation is handled in ASP.NET MVC.</p>
<p>Hope that helps. Be sure to take a look at the source download to see everything pulled together and one extra usability feature that I didn’t have time to cover.</p>
<h3>Source</h3>
<p><a href="http://encosia.com/source/WebForms-jq-validation-p2.zip" title="WebForms-jq-validation-p2.zip"><img src="http://encosia.com/blog/wp-content/uploads/2009/11/download-WebForms-jq-validation-p2.png" width="492" height="46" alt="Download WebForms-jq-validation-p2.zip" /></a></p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/">Emulate ASP.NET validation groups with jQuery validation</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/' rel='bookmark' title='Permanent Link: Using jQuery validation with ASP.NET WebForms'>Using jQuery validation with ASP.NET WebForms</a></li>
<li><a href='http://encosia.com/2008/10/11/using-jquery-to-display-a-modal-updatepanel-confirmation/' rel='bookmark' title='Permanent Link: Using jQuery to display a modal UpdatePanel confirmation'>Using jQuery to display a modal UpdatePanel confirmation</a></li>
<li><a href='http://encosia.com/2007/11/15/exploring-one-of-ms-ajaxs-often-overlooked-features/' rel='bookmark' title='Permanent Link: Exploring one of MS AJAX&#8217;s often overlooked features.'>Exploring one of MS AJAX&#8217;s often overlooked features.</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/feed/</wfw:commentRss>
		<slash:comments>38</slash:comments>
		</item>
		<item>
		<title>Using jQuery validation with ASP.NET WebForms</title>
		<link>http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/</link>
		<comments>http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 09:57:24 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=939</guid>
		<description><![CDATA[You’ve probably noticed that Jörn Zaefferer’s jQuery validation plugin has been gaining momentum in the ASP.NET community lately. Between Microsoft’s implied endorsement via ASP.NET MVC 2.0 integration and the plugin’s recent inclusion on the Microsoft AJAX CDN, adoption is only increasing. Unfortunately for those who don’t or can’t use ASP.NET MVC yet, using the validation [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/">Using jQuery validation with ASP.NET WebForms</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2008/10/04/using-jquery-to-enhance-aspnet-ajax-progress-indication/' rel='bookmark' title='Permanent Link: Using jQuery to enhance ASP.NET AJAX progress indication'>Using jQuery to enhance ASP.NET AJAX progress indication</a></li>
<li><a href='http://encosia.com/2008/10/31/use-jquery-and-quicksearch-to-interactively-search-any-data/' rel='bookmark' title='Permanent Link: Use jQuery and quickSearch to interactively search any data'>Use jQuery and quickSearch to interactively search any data</a></li>
<li><a href='http://encosia.com/2008/10/19/7-of-my-favorite-jquery-plugins-for-use-with-aspnet/' rel='bookmark' title='Permanent Link: 7 of my favorite jQuery plugins for use with ASP.NET'>7 of my favorite jQuery plugins for use with ASP.NET</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="border: 1px solid #333;" title="Validation Sticker" border="0" alt="Validation Sticker" src="http://encosia.com/blog/wp-content/uploads/2009/11/validation-sticker.jpg" width="490" height="138" /></p>
<p>You’ve probably noticed that Jörn Zaefferer’s <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" target="_blank">jQuery validation plugin</a> has been gaining momentum in the ASP.NET community lately. Between Microsoft’s implied endorsement via <a href="http://haacked.com/archive/2009/10/01/asp.net-mvc-preview-2-released.aspx" target="_blank">ASP.NET MVC 2.0 integration</a> and <a href="http://www.asp.net/ajax/CDN/#5" target="_blank">the plugin’s recent inclusion on the Microsoft AJAX CDN</a>, adoption is only increasing. Unfortunately for those who don’t or can’t use ASP.NET MVC yet, using the validation plugin within WebForms applications can be tricky.</p>
<p>Because the WebForms Postback model requires that the entire page be contained within a single form element, form submissions that shouldn’t trigger validation are likely. ASP.NET’s built-in validation controls solve this with ValidationGroups and the CausesValidation property, but that doesn’t help if you’d prefer to use the jQuery validation plugin.</p>
<p>However, there <em>are</em> a couple relatively easy workarounds that make it possible to use the jQuery validation plugin on WebForms pages, without re-architecting the page or its forms. In this post, I’ll show you <strong>why the WebForms page structure is a problem</strong>, how to <strong>make jQuery validation work with it</strong>, and <strong>an example of implementing those workarounds</strong>.</p>
<p><em>Note: I want to preface this by saying that you should never rely entirely on client-side validation. The jQuery validation plugin can be a great replacement for the client-side part of the ASP.NET Validators, but it is not a complete replacement on its own. Use responsibly!</em></p>
<h3>&lt;form&gt; over function</h3>
<p>When it comes to using jQuery validation, <strong>the trouble with WebForms is that it requires all of the ASP.NET controls on a page to be contained within a single form element</strong>. That doesn’t lead to any problems in simple demos, but things are more complicated when it comes to real-world pages. They often require multiple logical forms on the same page, and that’s where the problems start.</p>
<p>For example, consider the common scenario of having both a login form and a customer information form on the same page. We’ve probably all seen something like this before:</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #060; font-weight: bold;">&lt;</span>form id<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;form1&quot;</span> runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>
  <span style="color: #060; font-weight: bold;">&lt;</span>fieldset<span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>legend<span style="color: #060; font-weight: bold;">&gt;</span>Returning customer<span style="color: #060; font-weight: bold;">?</span>  Login here<span style="color: #060; font-weight: bold;">&lt;/</span>legend<span style="color: #060; font-weight: bold;">&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>label <span style="color: #909; font-weight: bold;">for</span><span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Username&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>Email<span style="color: #060; font-weight: bold;">:&lt;/</span>label<span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>TextBox runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Username&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>label <span style="color: #909; font-weight: bold;">for</span><span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Password&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>Password<span style="color: #060; font-weight: bold;">:&lt;/</span>label<span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>TextBox runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Password&quot;</span> TextMode<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Password&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>Button runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Login&quot;</span> Text<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Login&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
  <span style="color: #060; font-weight: bold;">&lt;/</span>fieldset<span style="color: #060; font-weight: bold;">&gt;</span>
&nbsp;
  <span style="color: #060; font-weight: bold;">&lt;</span>fieldset id<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;BillingInfo&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>legend<span style="color: #060; font-weight: bold;">&gt;</span>New customer<span style="color: #060; font-weight: bold;">?</span>  Provide the following<span style="color: #060; font-weight: bold;">&lt;/</span>legend<span style="color: #060; font-weight: bold;">&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>label <span style="color: #909; font-weight: bold;">for</span><span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;FirstName&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>First Name<span style="color: #060; font-weight: bold;">:&lt;/</span>label<span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>TextBox runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;FirstName&quot;</span> CssClass<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;required&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>label <span style="color: #909; font-weight: bold;">for</span><span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;LastName&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>Last Name<span style="color: #060; font-weight: bold;">:&lt;/</span>label<span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>TextBox runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;LastName&quot;</span> CssClass<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;required&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>label <span style="color: #909; font-weight: bold;">for</span><span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Address&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>Address<span style="color: #060; font-weight: bold;">:&lt;/</span>label<span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>TextBox runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Address&quot;</span> CssClass<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;required&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>label <span style="color: #909; font-weight: bold;">for</span><span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;City&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>City<span style="color: #060; font-weight: bold;">:&lt;/</span>label<span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>TextBox runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;City&quot;</span> CssClass<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;required&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>label <span style="color: #909; font-weight: bold;">for</span><span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;State&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>State<span style="color: #060; font-weight: bold;">:&lt;/</span>label<span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>TextBox runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;State&quot;</span> CssClass<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;required&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>label <span style="color: #909; font-weight: bold;">for</span><span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Zip&quot;</span><span style="color: #060; font-weight: bold;">&gt;</span>Zip<span style="color: #060; font-weight: bold;">:&lt;/</span>label<span style="color: #060; font-weight: bold;">&gt;</span>
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>TextBox runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Zip&quot;</span> CssClass<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;required&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
&nbsp;
    <span style="color: #060; font-weight: bold;">&lt;</span>asp<span style="color: #060; font-weight: bold;">:</span>Button runat<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;server&quot;</span> ID<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Order&quot;</span> Text<span style="color: #060; font-weight: bold;">=</span><span style="color: #c00;">&quot;Submit Order&quot;</span> <span style="color: #060; font-weight: bold;">/&gt;</span>
  <span style="color: #060; font-weight: bold;">&lt;/</span>fieldset<span style="color: #060; font-weight: bold;">&gt;</span>
<span style="color: #060; font-weight: bold;">&lt;/</span>form<span style="color: #060; font-weight: bold;">&gt;</span></pre></div></div>

<p>In most web frameworks, you would divide both logical forms into separate form elements, but WebForms requires both to remain joined within its single form element. This means that  <strong>clicking either of the Button controls will submit both logical forms together.</strong></p>
<p>Once applied to a form through <a href="http://docs.jquery.com/Plugins/Validation#Example" rel="nofollow" target="_blank">its default usage</a>, the jQuery validation plugin will attempt to validate all of the elements on that form <em>any time it is submitted</em>. That automation is usually handy, but it means <strong>users trying to submit our login form will be denied due to validation failing on the unrelated fields below</strong>.</p>
<p><img style="border: 1px solid #333;" src="http://encosia.com/blog/wp-content/uploads/2009/11/cross-validation-issue.jpg" width="490" height="416" /></p>
<p>Since using separate form elements containing WebForms controls isn’t realistic, we need to tackle this on the client-side and find a way to make jQuery validation more WebForms-friendly.</p>
<h3>Taming jQuery validation</h3>
<p>To remedy this problem, we first need to prevent the jQuery validation plugin from automatically triggering on every form submission. The initializer’s <strong>onsubmit</strong> property allows us to do just that:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Initialize validation on the entire ASP.NET form</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#form1&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">validate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// This prevents validation from running on every</span>
    <span style="color: #006600; font-style: italic;">//  form submission by default.</span>
    onsubmit<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>That fixes our problem of the login form triggering unwanted validation in the form below, but it creates another issue. Now, <em>neither</em> of the forms will validate when submitted.</p>
<h3>Taking control with on-demand validation</h3>
<p>Instead of relying on the plugin to automatically validate form submissions, you may also use a less widely known method for triggering the validation on-demand. When added to a page, one of the new methods that jQuery validation exposes on the jQuery object is <strong>valid()</strong>.</p>
<p>When <a href="http://docs.jquery.com/Plugins/Validation/valid" rel="nofollow" target="_blank">valid()</a> is called on the jQuery object returned from selecting a “validated” form element, it will trigger validation on every field within the form and return a Boolean value indicating whether or not the form is valid.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#form1&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">validate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    onsubmit<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Order&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>evt<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// Validate the form and retain the result.</span>
    <span style="color: #003366; font-weight: bold;">var</span> isValid <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#form1&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">valid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// If the form didn't validate, prevent the</span>
    <span style="color: #006600; font-style: italic;">//  form submission.</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>isValid<span style="color: #009900;">&#41;</span>
      evt.<span style="color: #660066;">preventDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>At first glance, this code might look incomplete to you. We care about more than just preventing form submissions when the form fails validation; we must also indicate the validation errors to the user.</p>
<p>Fortunately, <strong>the valid() method has the very useful side effect of displaying the plugin’s configured validation errors</strong> for any fields it finds to fail validation.</p>
<p>From the user’s perspective, this implementation is the same as the original one using the default usage. This method just happens to also have the added benefit of actually allowing returning users to log in.</p>
<h3>To be continued…</h3>
<p>This solution is a good start, but has (at least) two flaws.</p>
<p>First, it doesn’t handle keyboard triggered form submissions. <strong>What happens if the user hits the enter key in one of the TextBoxes</strong>?</p>
<p>Second, <strong>what if we want to also validate the login form</strong>? If validation rules are added to that form’s fields, we’ll have exactly the opposite problem as what we started with. Valid submissions in the lower form will be prevented by validation failures on the upper form.</p>
<p>For solutions to both of those problems, be sure to read my followup post: <a href="http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/">Emulate ASP.NET WebForms validation groups with jQuery validation</a>.</p>
<h3>Download the Source</h3>
<p><a href="/source/WebForms-jq-validation.zip"><img src="http://encosia.com/blog/wp-content/uploads/2009/11/download-webforms-jq-validation.png" width="492" height="46" alt="Download WebForms-jq-validation.zip" /></a></p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/">Using jQuery validation with ASP.NET WebForms</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2008/10/04/using-jquery-to-enhance-aspnet-ajax-progress-indication/' rel='bookmark' title='Permanent Link: Using jQuery to enhance ASP.NET AJAX progress indication'>Using jQuery to enhance ASP.NET AJAX progress indication</a></li>
<li><a href='http://encosia.com/2008/10/31/use-jquery-and-quicksearch-to-interactively-search-any-data/' rel='bookmark' title='Permanent Link: Use jQuery and quickSearch to interactively search any data'>Use jQuery and quickSearch to interactively search any data</a></li>
<li><a href='http://encosia.com/2008/10/19/7-of-my-favorite-jquery-plugins-for-use-with-aspnet/' rel='bookmark' title='Permanent Link: 7 of my favorite jQuery plugins for use with ASP.NET'>7 of my favorite jQuery plugins for use with ASP.NET</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/11/04/using-jquery-validation-with-asp-net-webforms/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Updated: See how I used Firebug to learn jQuery</title>
		<link>http://encosia.com/2009/09/21/updated-see-how-i-used-firebug-to-learn-jquery/</link>
		<comments>http://encosia.com/2009/09/21/updated-see-how-i-used-firebug-to-learn-jquery/#comments</comments>
		<pubDate>Mon, 21 Sep 2009 05:44:41 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=908</guid>
		<description><![CDATA[It was great to see all the positive responses to the screencast I recently recorded with Craig Shoemaker on how to use Firebug’s console to learn jQuery. That being my first screencast, I really appreciate all of your support. However, you almost unanimously commented that it was too difficult to read the commands typed at [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/09/21/updated-see-how-i-used-firebug-to-learn-jquery/">Updated: See how I used Firebug to learn jQuery</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2009/08/10/see-how-i-used-firebug-to-learn-jquery/' rel='bookmark' title='Permanent Link: See how I used Firebug to learn jQuery'>See how I used Firebug to learn jQuery</a></li>
<li><a href='http://encosia.com/2008/01/11/highslide-js-net-updated-v05/' rel='bookmark' title='Permanent Link: Highslide JS .NET Updated (v0.5)'>Highslide JS .NET Updated (v0.5)</a></li>
<li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>It was great to see all the positive responses to the screencast I recently recorded with Craig Shoemaker on how to use Firebug’s console to learn jQuery. That being my first screencast, I really appreciate all of your support.</p>
<p>However, you almost unanimously commented that it was too difficult to read the commands typed at the console, and you were right. So, Craig and I re-recorded the entire thing, paying extra attention to the legibility of the end result.</p>
<p>Craig also managed to edit the same content down to 9:59m this time, so you can watch it on YouTube if you prefer:</p>
<p><object width="492" height="389"><param name="movie" value="http://www.youtube.com/v/JB6MIV_lHI0&#038;hl=en&#038;fs=1&#038;rel=0&#038;ap=%2526fmt%3D18"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/JB6MIV_lHI0&#038;hl=en&#038;fs=1&#038;rel=0&#038;ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="492" height="389"></embed></object></p>
<p>If the HQ version of the YouTube video still isn’t legible enough for you, <a href="http://weblogs.asp.net/craigshoemaker/archive/2009/09/18/updated-video-for-using-firebug-and-jquery-post.aspx" target="_blank">Craig also made a full resolution WMV available as well</a>.</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/09/21/updated-see-how-i-used-firebug-to-learn-jquery/">Updated: See how I used Firebug to learn jQuery</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2009/08/10/see-how-i-used-firebug-to-learn-jquery/' rel='bookmark' title='Permanent Link: See how I used Firebug to learn jQuery'>See how I used Firebug to learn jQuery</a></li>
<li><a href='http://encosia.com/2008/01/11/highslide-js-net-updated-v05/' rel='bookmark' title='Permanent Link: Highslide JS .NET Updated (v0.5)'>Highslide JS .NET Updated (v0.5)</a></li>
<li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/09/21/updated-see-how-i-used-firebug-to-learn-jquery/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>Get early access to ASP.NET AJAX in Action, Second Edition</title>
		<link>http://encosia.com/2009/08/05/get-early-access-to-asp-net-ajax-in-action-second-edition/</link>
		<comments>http://encosia.com/2009/08/05/get-early-access-to-asp-net-ajax-in-action-second-edition/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 13:17:39 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Reading]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=893</guid>
		<description><![CDATA[If you’ve been reading long, you might remember that I’ve been a fan of ASP.NET AJAX in Action since the original was published. By avoiding heavy reliance on drag ‘n drop methodologies, the Manning book leaves readers with a deeper understanding of the framework. Without understanding the underlying mechanisms well, developing successful solutions is as [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/08/05/get-early-access-to-asp-net-ajax-in-action-second-edition/">Get early access to ASP.NET AJAX in Action, Second Edition</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2007/12/17/three-free-copies-of-aspnet-ajax-in-action-up-for-grabs/' rel='bookmark' title='Permanent Link: Three copies of ASP.NET AJAX in Action up for grabs'>Three copies of ASP.NET AJAX in Action up for grabs</a></li>
<li><a href='http://encosia.com/2007/12/20/three-copies-of-aspnet-ajax-in-action-still-available/' rel='bookmark' title='Permanent Link: Three copies of ASP.NET AJAX in Action still available'>Three copies of ASP.NET AJAX in Action still available</a></li>
<li><a href='http://encosia.com/2008/09/03/review-advanced-aspnet-ajax-server-controls/' rel='bookmark' title='Permanent Link: Review: Advanced ASP.NET AJAX Server Controls'>Review: Advanced ASP.NET AJAX Server Controls</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://manning.com/gallo2/" target="_blank"><img src="http://encosia.com/blog/wp-content/uploads/2009/08/asp-net-ajax-in-action-2e-cover-sm.png" alt="The book cover of ASP.NET AJAX in Action, 2nd Edition" style="float: left; margin: 5px 8px 10px 0; border: 1px solid #000;" /></a>If you’ve been reading long, you might remember that <a href="http://encosia.com/2007/12/17/three-free-copies-of-aspnet-ajax-in-action-up-for-grabs/">I’ve been a fan of ASP.NET AJAX in Action since the original was published</a>. By avoiding heavy reliance on drag ‘n drop methodologies, the Manning book leaves readers with a deeper understanding of the framework.</p>
<p>Without understanding the underlying mechanisms well, developing successful solutions is as much a function of luck as it is skill; especially when it comes to debugging and maintenance. So, I think a comprehensive book like this is absolutely essential.</p>
<h3>Now with more Encosia</h3>
<p>Already being a fan of the book, you can probably imagine my response when I got an email from <a href="http://aspadvice.com/blogs/garbin/" target="_blank">Alessandro</a> asking if I’d like to participate in the Second Edition. It was certainly the easiest decision I made that day, to say the least. I’ll be helping add new examples, writing about <a href="http://encosia.com/2008/07/23/sneak-peak-aspnet-ajax-4-client-side-templating/">ASP.NET AJAX 4.0’s new features</a>, and discussion about <a href="http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/">automating things like script compression</a>.</p>
<p>Though the book is still several months away from completion, <strong>three chapters are already available</strong> via the Manning Early Access Program (MEAP) for pre-orders. In fact, one chapter of the book is freely available, so be sure to check it out.</p>
<p>For a full ToC, the MEAP, and more information about the book, head over to the <a href="http://manning.com/gallo2/" target="_blank">ASP.NET AJAX in Action, Second Edition page on Manning’s site</a>.</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/08/05/get-early-access-to-asp-net-ajax-in-action-second-edition/">Get early access to ASP.NET AJAX in Action, Second Edition</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2007/12/17/three-free-copies-of-aspnet-ajax-in-action-up-for-grabs/' rel='bookmark' title='Permanent Link: Three copies of ASP.NET AJAX in Action up for grabs'>Three copies of ASP.NET AJAX in Action up for grabs</a></li>
<li><a href='http://encosia.com/2007/12/20/three-copies-of-aspnet-ajax-in-action-still-available/' rel='bookmark' title='Permanent Link: Three copies of ASP.NET AJAX in Action still available'>Three copies of ASP.NET AJAX in Action still available</a></li>
<li><a href='http://encosia.com/2008/09/03/review-advanced-aspnet-ajax-server-controls/' rel='bookmark' title='Permanent Link: Review: Advanced ASP.NET AJAX Server Controls'>Review: Advanced ASP.NET AJAX Server Controls</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/08/05/get-early-access-to-asp-net-ajax-in-action-second-edition/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Simplify calling ASP.NET AJAX services from jQuery</title>
		<link>http://encosia.com/2009/07/21/simplify-calling-asp-net-ajax-services-from-jquery/</link>
		<comments>http://encosia.com/2009/07/21/simplify-calling-asp-net-ajax-services-from-jquery/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 17:11:37 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=888</guid>
		<description><![CDATA[As jQuery’s popularity in the .NET community has risen over the past year, one recurring theme I’ve seen is the desire to refactor away the details of using it to call ASP.NET AJAX services. Whether through helper function or specialized jQuery plugin, I’ve seen numerous methods proposed and/or in use. Personally, the syntax never bothered [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/07/21/simplify-calling-asp-net-ajax-services-from-jquery/">Simplify calling ASP.NET AJAX services from jQuery</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/' rel='bookmark' title='Permanent Link: Using complex types to make calling services less&#8230; complex'>Using complex types to make calling services less&#8230; complex</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>As jQuery’s popularity in the .NET community has risen over the past year, one recurring theme I’ve seen is the desire to refactor away the details of using it to call ASP.NET AJAX services. Whether through helper function or specialized jQuery plugin, I’ve seen numerous methods proposed and/or in use.</p>
<p>Personally, the syntax never bothered me. The contentType parameter is ugly, but I have a Visual Studio code snippet for the $.ajax call and rarely think about it.</p>
<p>That came to an end earlier this year, when I started using dataFilter. I needed to <a href="http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/" target="_blank">isolate my code from the “.d” issue</a>, and wanted to <a href="http://encosia.com/2009/07/07/improving-jquery-json-performance-and-security/" target="_blank">take advantage of browser-native JSON parsing</a> in Firefox 3.5 and IE8, which required a bulky dataFilter.</p>
<p>Repeating that entire callback function in every $.ajax call was not acceptable. So, I was happy to learn that jQuery provides an excellent solution for consolidating settings to be used in multiple instances of $.ajax.</p>
<p>In this post, I’ll show you <strong>how to use that consolidation feature</strong>, and exactly how I am now using that to <strong>more simply call ASP.NET AJAX services with jQuery</strong>.</p>
<h3>Configuring $.ajax’s default settings</h3>
<p>Rather than wrapping the $.ajax call in a plugin or helper function, jQuery provides a built-in solution that I think is a better alternative:&#160; <a href="http://docs.jquery.com/Ajax/jQuery.ajaxSetup" target="_blank">$.ajaxSetup</a>.</p>
<p>$.ajaxSetup accepts an array of settings that allows you to supply defaults for any of the parameters that you would set in an $.ajax call. Settings like <strong>contentType</strong>, <strong>type</strong>, and <strong>dataFilter</strong> are all fair game, for example.</p>
<p>Using this function, it’s easy to set jQuery’s $.ajax defaults to match <a href="http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/" target="_blank">the refined settings that we worked out together last year</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajaxSetup</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{}&quot;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Because <strong>parameters to</strong> <strong>$.ajax override these defaults</strong>, presetting “data” to an empty JSON string is safe. Any $.ajax call that does specify a data parameter will function as expected, since the default will be ignored.</p>
<p>The particular issue caused by forgetting the empty data parameter can be difficult to track down, and only shows up after you’ve deployed your application to IIS. So, having the default as a safety net is recommended.</p>
<h3>Adding JSON parsing improvements</h3>
<p>Because $.ajaxSetup also supports setting a dataFilter, adding <a href="http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/" target="_blank">the “.d” isolation</a> and <a href="http://encosia.com/2009/07/07/improving-jquery-json-performance-and-security/" target="_blank">browser-native JSON parsing</a> from my last two posts is easy:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajaxSetup</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{}&quot;</span><span style="color: #339933;">,</span>
  dataFilter<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> msg<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span> <span style="color: #009900;">&#40;</span>JSON<span style="color: #009900;">&#41;</span> <span style="color: #339933;">!==</span> <span style="color: #3366CC;">'undefined'</span> <span style="color: #339933;">&amp;&amp;</span> 
        <span style="color: #000066; font-weight: bold;">typeof</span> <span style="color: #009900;">&#40;</span>JSON.<span style="color: #660066;">parse</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">'function'</span><span style="color: #009900;">&#41;</span>
      msg <span style="color: #339933;">=</span> JSON.<span style="color: #660066;">parse</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">else</span>
      msg <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'('</span> <span style="color: #339933;">+</span> data <span style="color: #339933;">+</span> <span style="color: #3366CC;">')'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>msg.<span style="color: #660066;">hasOwnProperty</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'d'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      <span style="color: #000066; font-weight: bold;">return</span> msg.<span style="color: #660066;">d</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">else</span>
      <span style="color: #000066; font-weight: bold;">return</span> msg<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This dataFilter processing is actually what pushed me to start using $.ajaxSetup in all of my own projects. It was one thing to accept multiple contentType and method declarations, but repeating the dataFilter for every $.ajax call was more than I could handle.</p>
<h3>Putting it to work</h3>
<p>With the ASP.NET AJAX defaults set in $.ajaxSetup, <strong>all that’s required to call a “ScriptService” or page method is the URL and a success callback</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;HelloWorld.asmx/Hello&quot;</span><span style="color: #339933;">,</span>
  success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>In fact, even the success callback is optional. For example, if you were periodically pinging a “heartbeat” service to keep the user’s session alive, $.ajax would only need the service&#8217;s URI.</p>
<p>This more concise syntax makes your service calls <em>far</em> more readable, especially for developers who aren’t familiar with the content-type required by ASP.NET AJAX. </p>
<h3>Caution: Sometimes it works too well</h3>
<p>While this is a handy way to simplify calls to ASP.NET AJAX services, do understand that <strong>$.ajaxSetup applies to all of jQuery’s AJAX derivatives</strong>. Setting the default HTTP method and content-type may also impact code and plugins that use jQuery’s built-in communication functionality (e.g. $.getJSON, $.post, etc).</p>
<p>For example, I often <a href="http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/" target="_blank">use jTemplates as a client-side templating solution</a>. Because its processTemplateURL routine relies on $.ajax to retrieve remote template files, setting the ASP.NET AJAX content-type and POST method in $.ajaxSetup breaks that functionality of jTemplates.</p>
<p>Fixing that problem wasn’t difficult, but it also wasn’t immediately obvious what had caused the issue in the first place. In my experience using this technique, the undesirable side effects are rare enough that it’s not a serious concern, but do be aware of the potential.</p>
<h3>Conclusion</h3>
<p>I’ve been using this in production for several months now, with great results. Users have noticed the increased speed that came with browser-native JSON parsing, the “.d” isolation has reduced regression errors due to some code we run on both 2.0 and 3.5 servers, and <strong>it requires less effort on my part to do all that</strong>.</p>
<p>What do you think? Is this helpful?</p>
<p>Would a Visual Studio template with this rolled in be something you would use?</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/07/21/simplify-calling-asp-net-ajax-services-from-jquery/">Simplify calling ASP.NET AJAX services from jQuery</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/' rel='bookmark' title='Permanent Link: Using complex types to make calling services less&#8230; complex'>Using complex types to make calling services less&#8230; complex</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/07/21/simplify-calling-asp-net-ajax-services-from-jquery/feed/</wfw:commentRss>
		<slash:comments>65</slash:comments>
		</item>
		<item>
		<title>Improving jQuery’s JSON performance and security</title>
		<link>http://encosia.com/2009/07/07/improving-jquery-json-performance-and-security/</link>
		<comments>http://encosia.com/2009/07/07/improving-jquery-json-performance-and-security/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 13:00:02 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=886</guid>
		<description><![CDATA[When you’re working with JSON, performance and security are often opposing, yet equally important concerns. One of these areas of contention is handling the JSON strings returned by a server. Most JavaScript libraries do a great job of abstracting away the details, but the underlying process has long been a frustrating exercise in compromise. On [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/07/07/improving-jquery-json-performance-and-security/">Improving jQuery’s JSON performance and security</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/' rel='bookmark' title='Permanent Link: Never worry about ASP.NET AJAX&#8217;s .d again'>Never worry about ASP.NET AJAX&#8217;s .d again</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>When you’re working with JSON, <strong>performance</strong> and <strong>security</strong> are often opposing, yet equally important concerns. One of these areas of contention is handling the JSON strings returned by a server. Most JavaScript libraries do a great job of abstracting away the details, but the underlying process has long been a frustrating exercise in compromise.</p>
<p>On one hand, eval() is the fastest widely available method, <a href="http://yuiblog.com/blog/2007/04/10/json-and-browser-security/" target="_blank">but it is not safe</a>.</p>
<p>On the other hand, textual JSON parsers written in JavaScript may be much safer, but are <strong>dramatically slower</strong>. In client-side situations, <a href="http://encosia.com/2009/06/09/11-keystrokes-that-made-my-jquery-selector-run-10x-faster/" target="_blank">where milliseconds count</a>, such a large performance overhead is typically too prohibitive to accept.</p>
<p>Recently, an exciting new alternative has emerged: <strong>browser-native JSON parsing</strong>. Integrating JSON parsing as part of the browser’s implementation of JavaScript allows for using the more secure parsing method, <em>and</em> even provides performance faster than eval() offers.</p>
<p>To take advantage of that, this post will show you how to <strong>detect whether or not a browser supports native JSON parsing</strong>, and how to <strong>force jQuery to use browser-native parsing</strong> in its $.ajax calls when it is available.</p>
<h3>Native JSON parsing in the browser</h3>
<p>Previously known as ECMAScript 3.1, ECMAScript “Fifth Edition” (the specification that JavaScript implements) formally codifies a native JSON parsing feature. The spec’s API exactly mirrors that of <a href="http://www.json.org/js.html" target="_blank">Crockford’s implementations of JSON.parse and JSON.stringify in json2.js</a>, easing the transition to browser-native functionality.</p>
<p>This native JSON parsing brings marked improvements in terms of <strong>both security and performance</strong>. Not only does the native routine use textual parsing to avoid the risk of executing malicious code embedded within JSON, but it is also <em>fast.</em></p>
<p>At the time of this writing, three major browsers <em>already</em> include support for native JSON parsing: <strong>IE8</strong>, <strong>Firefox 3.5</strong>, and <strong>Chrome 3</strong>.</p>
<p>Safari 4 does not currently support the standard, but its underlying engine (WebKit) <a href="https://bugs.webkit.org/show_bug.cgi?id=20031" rel="nofollow" target="_blank">has recently implemented it</a>. Hopefully the feature will make its way to Safari soon.</p>
<h3>Detecting native JSON support</h3>
<p>Determining whether or not native JSON parsing is available within a given browser is the first problem we need to solve. To do this, we ultimately need to know if the <strong>JSON.parse</strong> function is defined.</p>
<p>We can’t test for JSON.parse directly because attempting to reference it will throw a JavaScript error if the underlying JSON object doesn’t exist. So, first we need to inspect the type of that underlying object itself:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span><span style="color: #009900;">&#40;</span>JSON<span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">'object'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
  <span style="color: #006600; font-style: italic;">// native JSON may be available.</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>If we find that the JSON object does exist, it’s likely that native JSON parsing is available. However, it’s a best to double check the JSON.parse function as well:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span><span style="color: #009900;">&#40;</span>JSON.<span style="color: #660066;">parse</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">'function'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// native JSON parsing is available.</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Because JavaScript performs <a href="http://en.wikipedia.org/wiki/Short-circuit_evaluation" rel="nofollow" target="_blank">short-circuit evaluation</a>, it’s safe to clean this up by combining both tests in a single conditional, as long as they&#8217;re in this order:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span><span style="color: #009900;">&#40;</span>JSON<span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">'object'</span> <span style="color: #339933;">&amp;&amp;</span> 
    <span style="color: #000066; font-weight: bold;">typeof</span><span style="color: #009900;">&#40;</span>JSON.<span style="color: #660066;">parse</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">'function'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Native JSON parsing is available.</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Curious whether your browser supports native JSON parsing? Using the JavaScript above, I have determined that: <strong><script type="text/javascript">if (typeof(JSON) === 'object') { if (typeof(JSON.parse) === 'function') { document.write('It does!'); } } else { document.write('It does not.'); }</script></strong></p>
<p><noscript>You appear to have JavaScript disabled or are reading this in an RSS reader.  In order to view the status of your browser&#8217;s native JSON capability, <a target="_blank" href="http://encosia.com/2009/07/07/improving-jquery-json-performance-and-security/">please view this post in a browser with JavaScript enabled</a>.</noscript></p>
<h3>Extending jQuery to use native JSON parsing</h3>
<p>In my previous post, I demonstrated how to <a href="http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/" target="_blank">use jQuery’s dataFilter to transform a JSON response</a> before it is returned to the $.ajax() success handler. In the process, we also preempted jQuery’s default method for deserializing JSON data.</p>
<p>The focus at that time was implementing the same method for JSON parsing that jQuery uses by default, so eval() was still used. However, we can also use the same dataFilter mechanism to force browser-native JSON parsing instead.</p>
<p>Using our JSON parsing detection code and a dataFilter callback, upgrading jQuery to use browser-native parsing is simple:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Your usual $.ajax() URL, data, dataType, etc.</span>
  dataFilter<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span> <span style="color: #009900;">&#40;</span>JSON<span style="color: #009900;">&#41;</span> <span style="color: #339933;">!==</span> <span style="color: #3366CC;">'undefined'</span> <span style="color: #339933;">&amp;&amp;</span> 
        <span style="color: #000066; font-weight: bold;">typeof</span> <span style="color: #009900;">&#40;</span>JSON.<span style="color: #660066;">parse</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">'function'</span><span style="color: #009900;">&#41;</span>
      <span style="color: #000066; font-weight: bold;">return</span> JSON.<span style="color: #660066;">parse</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">else</span>
      <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'('</span> <span style="color: #339933;">+</span> data <span style="color: #339933;">+</span> <span style="color: #3366CC;">')'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Because jQuery only attempts to deserialize JSON responses if their type is string, and because the dataFilter callback executes <em>before</em> jQuery would normally perform that deserialization, this technique preempts jQuery’s JSON evaluation completely. In the worst case, it will simply revert back to the same eval() method that jQuery internally uses by default anyway.</p>
<p><em>Note: It’s important to keep in mind that the dataFilter will run regardless of what type is actually returned from the server. You should only use this when you’re sure that you’re receiving a JSON string.</em></p>
<h3>Conclusion</h3>
<p>If you’ve been paying close attention to jQuery’s ongoing development, you may already know that <a href="http://dev.jquery.com/ticket/4429" rel="nofollow" target="_blank">jQuery 1.3.3 will provide functionality very similar to what I’ve shown you</a>. I decided to go ahead and write this post anyway for a few reasons:</p>
<ul>
<li>You can use this <strong>today</strong>, without waiting for jQuery 1.3.3.</li>
<li>You can use this in previous versions of jQuery, if upgrading isn’t feasible for you (as is often the case with plugins dependent on older versions).</li>
<li>If you use <a href="http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/" target="_blank">my technique for isolating your code from ASP.NET AJAX’s “.d”</a>, you will still need a method for deserializing JSON in the dataFilter.</li>
</ul>
<p>Speaking of that last point, if you’re using jQuery with ASP.NET AJAX services, be sure to watch out for the next post in this (accidental) series. There is at least one more productive step left in improving this workflow that I have been using in my projects and want to share with you soon.</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/07/07/improving-jquery-json-performance-and-security/">Improving jQuery’s JSON performance and security</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/' rel='bookmark' title='Permanent Link: Never worry about ASP.NET AJAX&#8217;s .d again'>Never worry about ASP.NET AJAX&#8217;s .d again</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/07/07/improving-jquery-json-performance-and-security/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Never worry about ASP.NET AJAX&#8217;s .d again</title>
		<link>http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/</link>
		<comments>http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 05:00:48 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=883</guid>
		<description><![CDATA[When I recently received this message from a frustrated reader: After hours and hours of slamming my head into the desk it turns out it was the darn &#34;d&#34; in the response. My home computer is on .NET 2.0 and my work computer is on 3.5. Jimminie Christmas! I realized that the “.d” introduced in [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/">Never worry about ASP.NET AJAX&#8217;s .d again</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
<li><a href='http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/' rel='bookmark' title='Permanent Link: A breaking change between versions of ASP.NET AJAX'>A breaking change between versions of ASP.NET AJAX</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>When I recently received this message from a frustrated reader:</p>
<blockquote><p>After hours and hours of slamming my head into the desk it turns out it was the darn &quot;d&quot; in the response. My home computer is on .NET 2.0 and my work computer is on 3.5. <strong>Jimminie Christmas</strong>!</p></blockquote>
<p>I realized that the “.d” introduced in ASP.NET AJAX 3.5’s JSON responses is still all too common a stumbling block when <a target="_blank" href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/">calling ASP.NET AJAX services through a library such as jQuery</a>. In fact, with jQuery’s popularity among ASP.NET developers on the rise, this appears to have <strong>become an even more frequent problem</strong>.</p>
<p>Since a lot of people are having trouble with it, I want to share one method you can use to completely isolate your code from the problem. If you bake this into an $.ajax() code snippet or otherwise use it as a template for calling ASP.NET AJAX services in jQuery, you should never have to think or worry about the “.d” again.</p>
<p>In this post, I will show you <strong>how to detect the “.d”</strong> and how you can <strong>completely isolate your $.ajax success handler from it</strong>.</p>
<h3>“.d” what?</h3>
<p>If you aren’t familiar with the “.d” I’m referring to, it is simply a security feature that Microsoft added in ASP.NET 3.5’s version of ASP.NET AJAX. By encapsulating the JSON response within a parent object, the framework helps protect against <a href="http://haacked.com/archive/2009/06/25/json-hijacking.aspx" target="_blank">a particularly nasty XSS vulnerability</a>.</p>
<p>Before ASP.NET 3.5, “ScriptServices” and page methods returned their data at the top level of the JSON response, like this:</p>
<p><img title="2.0 JSON Response" border="0" alt="2.0 JSON Response in Firebug" src="http://encosia.com/blog/wp-content/uploads/2009/02/20-json-response.png" width="490" height="146" /></p>
<p>In ASP.NET 3.5 and later, the same server-side code returns this:</p>
<p><img title="3.5 JSON Response" border="0" alt="3.5 JSON Response in Firebug" src="http://encosia.com/blog/wp-content/uploads/2009/02/35-json-response.png" width="490" height="146" /></p>
<p>For more information about the change and <em>why</em> the change is a good one, be sure to see my earlier post: <a href="http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/" target="_blank">A breaking change between versions of ASP.NET AJAX</a>.</p>
<p>However, what my previous post lacks is a solution for mitigating the inconsistency entirely. Using different client-side code against 2.0 and 3.5 based services is workable, but far from ideal. <strong>Wouldn’t it be nicer to not have to worry about it?</strong></p>
<h3>Determining whether or not the “.d” is there</h3>
<p>In order to isolate ourselves from the “.d”, we first need a reliable way to test for its presence. Though JavaScript provides several methods for determining this, I suggest hasOwnProperty, <a href="http://encosia.com/2009/02/16/review-the-best-javascript-book-i%E2%80%99ve-read/" rel="nofollow" target="_blank">as recommended by Douglas Crockford</a>.</p>
<p>By using hasOwnProperty, your code is protected against <a href="http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/" target="_blank">unexpected changes to an object’s prototype chain</a>. Though it is an unlikely problem to encounter, it’s always best to code defensively in JavaScript. The browser is a hostile environment!</p>
<p>Using hasOwnProperty to test for “.d”, you might end up with something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;WebService.asmx/MethodName&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{}&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;json&quot;</span><span style="color: #339933;">,</span>
  success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>msg.<span style="color: #660066;">hasOwnProperty</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;d&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      <span style="color: #006600; font-style: italic;">// Leave the .d behind and pass the rest of </span>
      <span style="color: #006600; font-style: italic;">//  the JSON object forward.</span>
      DoSomething<span style="color: #009900;">&#40;</span>msg.<span style="color: #660066;">d</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">else</span>
      <span style="color: #006600; font-style: italic;">// No .d; no transformation necessary.</span>
      DoSomething<span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> DoSomething<span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Do something with the response data here.</span>
  <span style="color: #006600; font-style: italic;">//  Expect it to consistently have no .d.</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This code <em>will</em> perform identically against any version of ASP.NET AJAX.</p>
<p>Unfortunately, this might still get in your way. You may not always want to use the response in a call to another function, and you’ll have to remember the conditional every time you write a success handler.</p>
<h3>Don’t make me think</h3>
<p>I prefer a solution that doesn’t touch the success handler at all. Then, you’re free to integrate the “.d” handling into a generic $.ajax code snippet in Visual Studio and/or easily copy-paste it between files without modification.</p>
<p>Luckily, jQuery provides a mechanism that allows us to do just that: <strong>dataFilter</strong>.</p>
<p>The dataFilter parameter to $.ajax allows you to arbitrarily transform a response <em>just before</em> the success handler fires. Specifically tailored to this sort of situation, it passes response data into a callback function, captures the return value of that callback, and then passes the modified data into your success handler.</p>
<p>Hence, you can forever stop worrying about that pesky “.d” like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;WebService.asmx/MethodName&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{}&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  dataFilter<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// This boils the response string down </span>
    <span style="color: #006600; font-style: italic;">//  into a proper JavaScript Object().</span>
    <span style="color: #003366; font-weight: bold;">var</span> msg <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'('</span> <span style="color: #339933;">+</span> data <span style="color: #339933;">+</span> <span style="color: #3366CC;">')'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// If the response has a &quot;.d&quot; top-level property,</span>
    <span style="color: #006600; font-style: italic;">//  return what's below that instead.</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>msg.<span style="color: #660066;">hasOwnProperty</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'d'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      <span style="color: #000066; font-weight: bold;">return</span> msg.<span style="color: #660066;">d</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">else</span>
      <span style="color: #000066; font-weight: bold;">return</span> msg<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
  success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// This will now output the same thing </span>
    <span style="color: #006600; font-style: italic;">//  across any current version of .NET.</span>
    console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>msg.<span style="color: #660066;">foo</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Now, regardless which of these JSON forms the server returns:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// ASP.NET 2.0 with the ASP.NET AJAX Extensions installed.</span>
<span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'foo'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'bar'</span><span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// ASP.NET 3.5 and 4.0.</span>
<span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'d'</span><span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'foo'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'bar'</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>Your success handler will simply receive this consistent JSON object every time:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'foo'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'bar'</span><span style="color: #009900;">&#125;</span></pre></div></div>

<h3>dataType: none of your business</h3>
<p>It&#8217;s important to note the removal of the dataType parameter in the $.ajax() code above. This is required in order to prevent a double-eval of service responses containing only a single string.</p>
<p>Internally, jQuery uses a combination of the dataType parameter and the implicit type the response. If the dataType is &quot;json&quot; and typeof(response) is “string”, then jQuery uses eval() to deserialize the response.</p>
<p>In the example above, manually deserializing the response in dataFilter results in it being of type Object, jQuery leaves it alone, and our dataFilter’d object makes its way back to the success callback either way.</p>
<p>However, if the dataType is set to “json” and the “.d” sanitized response happens to be of JavaScript type “string”, jQuery will assume that it is a JSON response from the server and still needs to be deserialized. That will throw an error at best.</p>
<p>The solution is to simply drop the dataType parameter from the $.ajax() call. It is only needed for purposes of instructing jQuery how to deserialize the response, and we’re handling that ourselves now.</p>
<p>Thanks to Brett <a href="#comment-35702">for pointing this out</a>.</p>
<h3>Wait, isn’t eval() supposed to be evil?</h3>
<p>If the eval() usage gives you pause, don’t worry. For now (as of jQuery 1.3.2), this is the same mechanism that jQuery uses to deserialize JSON too. Though eval() <em>is</em> potentially evil, <strong>it is still a necessary evil in many browsers</strong>.</p>
<p>In my next post, I’ll show you how to modify this to leverage a native browser implementation of JSON.parse instead of eval(), available in some newer browsers.</p>
<p>That post is available now: <a href="http://encosia.com/2009/07/07/improving-jquery-json-performance-and-security/">Improving jQuery&#8217;s JSON performance and security</a>.</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/">Never worry about ASP.NET AJAX&#8217;s .d again</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
<li><a href='http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/' rel='bookmark' title='Permanent Link: A breaking change between versions of ASP.NET AJAX'>A breaking change between versions of ASP.NET AJAX</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
		<item>
		<title>Automatically minify and combine JavaScript in Visual Studio</title>
		<link>http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/</link>
		<comments>http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/#comments</comments>
		<pubDate>Wed, 20 May 2009 17:42:14 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=868</guid>
		<description><![CDATA[As you begin developing more complex client-side functionality, managing the size and shape of your JavaScript includes becomes a key concern. It’s all too easy to accidentally end up with hundreds of kilobytes of JavaScript spread across many separate HTTP requests, significantly slowing down your initial page loads. To combat this, it’s important to combine [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/">Automatically minify and combine JavaScript in Visual Studio</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2009/01/04/how-to-rotate-javascript-ads-during-aspnet-ajax-requests/' rel='bookmark' title='Permanent Link: How to rotate JavaScript ads during ASP.NET AJAX requests'>How to rotate JavaScript ads during ASP.NET AJAX requests</a></li>
<li><a href='http://encosia.com/2007/08/16/updated-your-webconfig-but-sys-is-still-undefined/' rel='bookmark' title='Permanent Link: Updated your web.config, but Sys is still undefined?'>Updated your web.config, but Sys is still undefined?</a></li>
<li><a href='http://encosia.com/2007/08/23/seamless-inline-text-editing-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: Seamless inline text editing with ASP.NET AJAX'>Seamless inline text editing with ASP.NET AJAX</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>As you begin developing more complex client-side functionality, managing the size and shape of your JavaScript includes becomes a key concern. It’s all too easy to accidentally end up with hundreds of kilobytes of JavaScript spread across many separate HTTP requests, significantly slowing down your initial page loads.</p>
<p>To combat this, <strong>it’s important to combine and compress your JavaScript</strong>. While there are useful standalone tools and HttpHandler based solutions to the problem already, none of them work quite how I prefer. Instead, I’m going to show you my dead-simple method for automatically compressing and combining script includes.</p>
<p>To accomplish that in this post, we will <strong>select a compression utility</strong>,<strong> learn how to use it</strong> at the command line, <strong>explore a useful automation feature</strong> in Visual Studio, and apply that to keep scripts combined and compressed with no ongoing effort.</p>
<h3>Selecting a JavaScript compression tool</h3>
<p>The first thing we’ll need is a utility to compress our JavaScript. There are many utilities available, ranging from <strong>YUI Compressor</strong> to Dean Edwards’ <strong>Packer</strong>, each with its own strengths and weaknesses.</p>
<p><a href="http://developer.yahoo.com/yui/compressor/" target="_blank">YUI Compressor</a> is powerful, but requires a Java runtime be available during the build process. <a href="http://dean.edwards.name/packer/" target="_blank">Packer</a> is popular for its Base62 encoding mode, however that form of compression carries <a href="http://ejohn.org/blog/library-loading-speed/" target="_blank">a non-trivial performance tax on the client-side</a>.</p>
<p>In terms of simplicity, it’s hard to beat <a href="http://www.crockford.com/javascript/jsmin.html" target="_blank">Douglas Crockford’s JSMin</a>. It requires no command line options, no runtimes or frameworks, and accepts input directly from standard input (which will be useful for us later).</p>
<p>One common concern about JSMin is that it outputs less compact code than YUI Compressor and Packer on their most aggressive settings. However, this is a bit of a red herring. When gzipped, the result of all three boil down to almost exactly the same size across the wire. Since you should <a href="http://www.julienlecomte.net/blog/2007/08/13/" target="_blank">always serve your JavaScript with gzip compression at the HTTP level</a>, this initial “disadvantage” is moot.</p>
<h3>Using JSMin from the command line</h3>
<p>Using JSMin is very straightforward. For example, say we have the following, well-commented JavaScript and want to minify it:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// how many times shall we loop? </span>
<span style="color: #003366; font-weight: bold;">var</span> foo <span style="color: #339933;">=</span> <span style="color: #CC0000;">10</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// what message should we use? </span>
<span style="color: #003366; font-weight: bold;">var</span> bar <span style="color: #339933;">=</span> <span style="color: #3366CC;">'Encosia'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// annoy our user with O(foo) alerts! </span>
<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> foo<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
  <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>bar<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Assuming that JavaScript is in a file called AlertLoop.js, this command line usage of JSMin will minify it and output it to the console:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">jsmin &lt; AlertLoop.js</pre></div></div>

<p><img title="jsmin-stdin" border="0" alt="jsmin-stdin" src="http://encosia.com/blog/wp-content/uploads/2009/05/jsmin-stdin.png" width="492" height="123" /></p>
<p>What this does is run jsmin and feed the contents of AlertLoop.js into standard input. It’s the same as if you had run jsmin and then typed all that JavaScript on the command line.</p>
<p>Similarly, this usage does the trick if you want to redirect that output to a file:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">jsmin &lt; AlertLoop.js &gt; AlertLoop.min.js</pre></div></div>

<p><img title="jsmin-to-file" border="0" alt="jsmin-to-file" src="http://encosia.com/blog/wp-content/uploads/2009/05/jsmin-to-file.png" width="492" height="154" /> </p>
<p>The minified output is less than half the size of the original. Not bad!</p>
<p><em>Note: If you’re wondering about the upper ASCII characters preceding the minified script, they’re nothing to be concerned about. Because I had created AlertLoop.js in Visual Studio, it was saved as UTF-8 by default and those characters are the UTF BOM (thanks to Oleg, Sugendran, and Bart <a href="http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/#comment-35349">for clarification</a>).</em></p>
<h3>Set up project directories</h3>
<p><img style="float: right; border: 1px solid #000; margin-left: 10px;" title="project-layout" border="0" alt="project-layout" align="right" src="http://encosia.com/blog/wp-content/uploads/2009/05/project-layout.png" width="231" height="275" />Before we get to the next steps, we need to define a structure for our project. The one shown to the right works for simple projects.</p>
<p>Within the website project, the important takeaway is that the JavaScript files to be compressed are all in the same directory and named with a <strong>*.debug.js</strong> pattern.</p>
<p>Outside of the website, notice the “tools” directory which contains a copy of JSMin. I think we can all agree that executables should not be included within a website project if possible. <strong>That would just be begging for trouble</strong>.</p>
<p>However, I do suggest including an external tools directory and JSMin executable in your project’s source control. You never want to create a scenario where someone can’t perform a checkout and then a successful build immediately afterward.</p>
<h3>Automation: Visual Studio earns its keep</h3>
<p>To automate script compression as part of the build process, I suggest using a <strong>build event</strong>. There are perfectly legitimate alternatives, but I prefer having a tangible file sitting on disk and having that compression process automated. So, “building” the minified JavaScript include(s) as part of the build process makes the most sense to me.</p>
<p>Build events may sound complicated, but they aren’t at all. Build events are simply <a href="http://msdn.microsoft.com/en-us/library/ke5z92ks(VS.80).aspx" target="_blank">a mechanism for executing command line code before and/or after your project is compiled</a>.</p>
<p>For our purposes, a post-build event is perfect. Additionally, we can specify that it should only run the build event if the project builds successfully. That way we avoid wasting unnecessary time on minifying the JavaScript when there are build errors.</p>
<h3>Setting up a build event in Visual Studio</h3>
<p>To add build events, right-click on your project and choose <strong>properties</strong>. In the properties page that opens, click on the “Build Events” tab to the left. You’ll be presented with something similar to this:</p>
<p><img title="project-properties" border="0" alt="project-properties" src="http://encosia.com/blog/wp-content/uploads/2009/05/project-properties.png" width="492" height="412" /></p>
<p><em>Note: If you’re using Visual Basic, there will be no build events tab in the project properties. Instead, look for a build events button on the “Build” tab, which allows access the same functionality.</em></p>
<p>You can type commands directly in the post-build field if you want, but clicking the “Edit Post-build” button provides a better editing interface:</p>
<p><img title="post-build-events" border="0" alt="post-build-events" src="http://encosia.com/blog/wp-content/uploads/2009/05/post-build-events.png" width="492" height="272" /></p>
<p>The interface’s macro list is especially useful. In particular, the <strong>ProjectDir</strong> macro will be handy for what we’re doing. $(ProjectDir) placed anywhere in a build event will be replaced with the actual project path, <strong>including a trailing backslash</strong>.</p>
<p>For example, we can use it to execute JSMin.exe in the hierarchy described above:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>..\tools\jsmin.exe</pre></div></div>

<p>Or, reference that same project’s js directory:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\</pre></div></div>

<h3>Putting it all together: Minify a single file</h3>
<p>Now that we’ve covered how to use JSMin at the command line and how to execute command line scripts as part of Visual Studio builds, putting it all together is easy.</p>
<p>For example, to minify default.debug.js, this post-build event will do the trick:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>..\tools\jsmin&quot; &lt; 
&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\default.debug.js&quot; &gt; 
&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\default.min.js&quot;</pre></div></div>

<p><em>(The line breaks are for readability here. The command in your actual build event must not contain them, or it will be interpreted as separate commands and fail.)</em></p>
<p>The quotes are important, in case $(ProjectDir) happens to include directories with spaces in their names. Since you never know where this project may eventually be built at, it’s best to always use the quotes.</p>
<h3>*Really* putting it together: Combine files</h3>
<p>I did promise more than just compression in the post’s title. <a href="http://developer.yahoo.com/performance/rules.html" target="_blank">Combining scripts is just as important as compression</a>, if not more so. Since JSMin takes its input from stdin, it’s easy to roll scripts together for minification into a single result:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">type &quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\*.debug.js&quot; | 
&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>..\tools\jsmin&quot; &gt; 
&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\script-bundle.min.js&quot;</pre></div></div>

<p>This build event would combine all of our *.debug.js scripts, minify the combined script bundle, and then output it in a new file named script-bundle.min.js.</p>
<p>This is great if you want to combine your most commonly used jQuery plugins into a single payload, for example. A reduction in HTTP requests usually provides a nice improvement in performance. This is especially true when you’re dealing with JavaScript, because the browser blocks while script references load.</p>
<h3>Dealing with dependencies</h3>
<p>Cross-dependencies between scripts is one issue that requires extra consideration when combining. Just the same as ordering script includes incorrectly, bundling scripts together in the wrong order may cause them to fail.</p>
<p>One relatively easy way to handle this is to give your scripts prefixes to force the correct order. For example, the source sample below includes this set of JavaScript files:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">default.debug.js
jQuery-1.3.2.debug.js
jQuery-jtemplates.debug.js</pre></div></div>

<p>Combining these and referencing the result will fail, because default.debug.js is sorted ahead both jQuery and the plugin by default. Since default.debug.js depends on both of those, this is a big problem. To fix this, rename the files with prefixes:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">01-jQuery.debug.js
05-jQuery-jtemplates.debug.js
<span style="color: #cc66cc;">10</span>-default.debug.js</pre></div></div>

<p>Now it will work perfectly.</p>
<p>Any system of alphanumeric prefixes will work, but be sure to pad numbers with leading zeroes if you use a numeric system. Otherwise, the default sort ordering may catch you off guard (e.g. 2-file.js sorts ahead of 11-file.js through 19-file.js).</p>
<h3>To debug, or not to debug</h3>
<p>Now that we have the minification process under control, one final issue to address is <strong>how to keep this from complicating our development workflow</strong>.</p>
<p>While editing these scripts, we certainly don’t want to be forced to recompile every time we make a change to the JavaScript. After all, one of the nice things about JavaScript is that it <em>doesn’t</em> require precompilation. Even worse, using a JavaScript debugger against minified files is a nightmare I wouldn’t recommend to anyone. </p>
<p>The easiest way I know of to ensure that the correct scripts are emitted for both scenarios is to <a href="http://www.west-wind.com/Weblog/posts/10228.aspx" target="_blank">check the IsDebuggingEnabled property of the HttpContext</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;head&gt;</span></span>
<span style="color: #009900;">&lt;% if <span style="color: #66cc66;">&#40;</span>HttpContext.Current.IsDebuggingEnabled<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> %<span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;script</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;js/01-jquery-1.3.2.debug.js&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span>script&gt;</span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;script</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;js/05-jquery-jtemplates.debug.js&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span>script&gt;</span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;script</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;js/10-default.debug.js&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span>script&gt;</span>
<span style="color: #009900;">&lt;% <span style="color: #66cc66;">&#125;</span> else <span style="color: #66cc66;">&#123;</span> %<span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;script</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;js/js-bundle.min.js&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span>script&gt;</span>
<span style="color: #009900;">&lt;% <span style="color: #66cc66;">&#125;</span> %<span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/head&gt;</span></span></pre></div></div>

<p>When the web.config’s compilation mode is set to debug, the *.debug.js versions of the files are referenced, and the auto-minified bundle otherwise. Now we have the best of both worlds.</p>
<h3>Conclusion</h3>
<p>I hope you’ll find that this technique is a good compromise between the tedium of using manual minification tools and the overwrought complexity of setting up some of the more “<a href="http://en.wikipedia.org/wiki/Enterprise_software" rel="nofollow" target="_blank">enterprisey</a>” automation solutions.</p>
<p>One not-so-obvious benefit that I’ve noticed stems from minification’s automatic comment stripping. Without worry about your comments burdening the size of the client-side payload or being distributed across the Internet, you’re more likely to comment your JavaScript well. Dealing with a dynamic language, sans-compiler, I find that <strong>comments are often crucial to maintainability</strong>.</p>
<p>This is one of those problems with quite a few perfectly legitimate solutions. What do you think of this solution? How do you normally handle this?</p>
<h3>Get the source</h3>
<p>For demonstration, I took my <a href="http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/" target="_blank">jQuery client-side repeater example</a> and applied this technique. Having several JavaScript includes (one that’s full of comments), it’s a perfect candidate for combining and compression.</p>
<p>One particular thing to notice in this example is the use of numeric prefixes to order the JavaScript includes, as mentioned earlier. This naming scheme is <strong>crucial when dealing with interdependent scripts</strong>. If the scripts are combined in the wrong order, your functionality will break just the same as if you had used script reference tags in the wrong order.</p>
<p><a href="http://encosia.com/source/jsmin-build.zip"><img title="jsmin-build.zip" border="0" alt="Download Source: jsmin-build.zip" src="http://encosia.com/blog/wp-content/uploads/2009/05/download-bar-jsmin-build.png" width="492" height="46" /></a></p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/">Automatically minify and combine JavaScript in Visual Studio</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2009/01/04/how-to-rotate-javascript-ads-during-aspnet-ajax-requests/' rel='bookmark' title='Permanent Link: How to rotate JavaScript ads during ASP.NET AJAX requests'>How to rotate JavaScript ads during ASP.NET AJAX requests</a></li>
<li><a href='http://encosia.com/2007/08/16/updated-your-webconfig-but-sys-is-still-undefined/' rel='bookmark' title='Permanent Link: Updated your web.config, but Sys is still undefined?'>Updated your web.config, but Sys is still undefined?</a></li>
<li><a href='http://encosia.com/2007/08/23/seamless-inline-text-editing-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: Seamless inline text editing with ASP.NET AJAX'>Seamless inline text editing with ASP.NET AJAX</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/feed/</wfw:commentRss>
		<slash:comments>71</slash:comments>
		</item>
		<item>
		<title>What ASP.NET developers should know about jQuery</title>
		<link>http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/</link>
		<comments>http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/#comments</comments>
		<pubDate>Wed, 13 May 2009 17:10:41 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=855</guid>
		<description><![CDATA[As much as I enjoyed attending MIX09 this year, it wasn’t a difficult decision when Karsten asked me to write an article for the MIX Online site. Reading this here, there’s a good chance the article is targeted below the amount of jQuery expertise you already have. However, it’s been brought to my attention that [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/">What ASP.NET developers should know about jQuery</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
<li><a href='http://encosia.com/2008/10/10/altnet-podcast-jquery-in-aspnet/' rel='bookmark' title='Permanent Link: Alt.NET Podcast &ndash; jQuery in ASP.NET'>Alt.NET Podcast &ndash; jQuery in ASP.NET</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>As much as I enjoyed attending <a href="http://live.visitmix.com/" target="_blank">MIX09</a> this year, it wasn’t a difficult decision when <a href="http://visitmix.com/About/karstenj" target="_blank">Karsten</a> asked me to write an article for the MIX Online site.</p>
<p>Reading this here, there’s a good chance the article is targeted below the amount of jQuery expertise you already have. However, it’s been brought to my attention that some readers have found it useful for sending to their more JavaScript-phobic coworkers.</p>
<p>So, I decided that it’s worth mentioning here after all:</p>
<blockquote><p>It’s hard to believe that <strong>JavaScript is already well over a decade old</strong>. Often relegated to marginal tasks in its early years, JavaScript has grown to become a pillar of modern web development. With the current popularity of DHTML and AJAX, it can be difficult to find a site that <strong>doesn’t</strong> use JavaScript anymore. One of the driving forces behind JavaScript’s newfound popularity is a proliferation of JavaScript frameworks, such as <strong>jQuery</strong>.</p>
<p>&#160;</p>
<p>Why?</p></blockquote>
<p><a class="more-link" href="http://visitmix.com/Opinions/What-ASPNET-Developers-Should-Know-About-jQuery" target="_blank">Click here to continue reading this article on the MIX Online site &raquo;</a></p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/">What ASP.NET developers should know about jQuery</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/' rel='bookmark' title='Permanent Link: Using jQuery to directly call ASP.NET AJAX page methods'>Using jQuery to directly call ASP.NET AJAX page methods</a></li>
<li><a href='http://encosia.com/2008/10/10/altnet-podcast-jquery-in-aspnet/' rel='bookmark' title='Permanent Link: Alt.NET Podcast &ndash; jQuery in ASP.NET'>Alt.NET Podcast &ndash; jQuery in ASP.NET</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How I handle JSON dates returned by ASP.NET AJAX</title>
		<link>http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/</link>
		<comments>http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 15:22:44 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=853</guid>
		<description><![CDATA[The problem of how to handle dates in JSON is one of the more troublesome issues that may arise when directly calling ASP.NET AJAX web services and page methods. Unlike every other data type in the language, JavaScript offers no declarative method for expressing a Date. Consequently, embedding them within JSON requires a bit of [...]<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/">How I handle JSON dates returned by ASP.NET AJAX</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>



Related posts:<ol><li><a href='http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/' rel='bookmark' title='Permanent Link: A breaking change between versions of ASP.NET AJAX'>A breaking change between versions of ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="border: 1px solid #000;" title="image" border="0" alt="A calendar" src="http://encosia.com/blog/wp-content/uploads/2009/04/calendar-blocks.jpg" width="490" height="215" /></p>
<p>The problem of how to handle dates in JSON is one of the more troublesome issues that may arise when <em>directly</em> calling ASP.NET AJAX web services and page methods.</p>
<p>Unlike every other data type in the language, <strong>JavaScript offers no declarative method for expressing a Date</strong>. Consequently, embedding them within JSON requires a bit of fancy footwork. Since the question of how I handle this problem is something asked often in emails and in comments on other posts here, I want to address the topic with its own post.</p>
<p>To that end, I will attempt to explain <strong>what exactly the problem is</strong> with dates in JSON, <strong>how ASP.NET AJAX solves it</strong>, and <strong>my alternative solution</strong> that I believe is easier and works just as well in most cases.</p>
<h3>What’s the problem?</h3>
<p>The fundamental problem is that JavaScript does not provide a way to declaratively express <a href="http://www.w3schools.com/jS/js_obj_date.asp" rel="nofollow" target="_blank">Date objects</a>. You may previously have seen this <a href="http://www.nikhilk.net/DateSyntaxForJSON.aspx" target="_blank">described as (the lack of) <strong>a Date literal</strong></a>.</p>
<p>What are literals? To illustrate, these are literals for several other data types:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// String</span>
<span style="color: #3366CC;">'foo'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Number</span>
<span style="color: #CC0000;">3.14</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Boolean</span>
<span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Array</span>
<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">7</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Object</span>
<span style="color: #009900;">&#123;</span> pi<span style="color: #339933;">:</span> <span style="color: #CC0000;">3.14</span><span style="color: #339933;">,</span> phi<span style="color: #339933;">:</span> <span style="color: #CC0000;">1.62</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Unfortunately, when it comes to dates, the lack of a literal means that the only way to create one is by explicitly initializing a Date object:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Correct.</span>
<span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'4/26/09'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Correct (the month is 0 indexed, hence the 3).</span>
<span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2009</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">26</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Incorrect. This is a string, not a Date.</span>
<span style="color: #3366CC;">'4/26/09'</span><span style="color: #339933;">;</span></pre></div></div>

<p>While this limitation is fine when writing client-side JavaScript code, it leaves us without a good way to transmit dates within JSON objects.</p>
<h3>How ASP.NET AJAX handles it</h3>
<p>While the lack of a date literal is a problem, it’s certainly not without solution.</p>
<p>In fact, ASP.NET AJAX <strong>already handles this</strong> if you’re using MicrosoftAjax.js to call your services. You may not have even noticed as server-side DateTime values are transparently converted into JavaScript Date objects on the client-side.</p>
<p>For example, consider this web service:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span><span style="color: #000000;">System.<span style="color: #0000FF;">Web</span></span>.<span style="color: #0000FF;">Script</span>.<span style="color: #0000FF;">Services</span>.<span style="color: #0000FF;">ScriptService</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> DateService <span style="color: #008000;">:</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Web</span>.<span style="color: #0000FF;">Services</span></span>.<span style="color: #0000FF;">WebService</span>
<span style="color: #000000;">&#123;</span>
  <span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> DateTime GetDate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> DateTime<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2009</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">26</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>If you <a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/" target="_blank">consume that web service with jQuery</a> (or any method that circumvents the ScriptManager), you’ll find that ASP.NET AJAX serializes the DateTime as an escaped JavaScript Date initializer:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;d&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;<span style="color: #000099; font-weight: bold;">\/</span>Date(1240718400000)<span style="color: #000099; font-weight: bold;">\/</span>&quot;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p><em>Note: If you&#8217;re unsure about why the &#8220;d&#8221; is there, be sure to see <a href="http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/">my recent post about this security feature which was added in ASP.NET 3.5</a>.</em></p>
<p>On the client-side, MicrosoftAjax.js uses a regular expression to isolate any Date constructors and then eval() to initialize Date objects. The end result is that proper JavaScript Date objects are instantiated for every DateTime value returned.</p>
<p>However, if you’re <em>not</em> using MicrosoftAjax.js (i.e. the ScriptManager) to call your services, you’ve got a bit of a mess to decode. You can <a href="http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx" target="_blank">use regex machinations to work around the problem</a>, but is that really necessary?</p>
<h3>How I handle it</h3>
<p>Consider <em>why</em> you want to send a DateTime to the client-side to begin with. Most often, you’re <strong>displaying a string representation of it</strong> and have no need for the proper JavaScript Date object.</p>
<p>What’s more, if you end up with a JavaScript Date object, you’ll probably use additional code or a JavaScript library to <strong>display it in a user-friendly format</strong>.</p>
<p>As much as I appreciate a clever workaround, I’d much rather avoid the problem completely. Rather than jump through all of these hoops to instantiate a JavaScript Date object on the client-side and then format it, <strong>I suggest simply returning a formatted string</strong>.</p>
<p>For example, we might modify the previous example like so:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#91;</span>System.<span style="color: #660066;">Web</span>.<span style="color: #660066;">Script</span>.<span style="color: #660066;">Services</span>.<span style="color: #660066;">ScriptService</span><span style="color: #009900;">&#93;</span>
<span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">class</span> DateService <span style="color: #339933;">:</span> System.<span style="color: #660066;">Web</span>.<span style="color: #660066;">Services</span>.<span style="color: #660066;">WebService</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #009900;">&#91;</span>WebMethod<span style="color: #009900;">&#93;</span>
  <span style="color: #003366; font-weight: bold;">public</span> string GetDate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2009</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">26</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ToLongDateString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now, calling the service will return this JSON:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;d&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Sunday, April 26, 2009&quot;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>No more regular expressions. No more JavaScript Date objects. No more worrying about formatting the data on the client-side.</p>
<p>Even better, no functionality is lost. If we need to instantiate Dates, we still can.</p>
<h3>Still want Dates?</h3>
<p>Even if you <em>do</em> end up needing JavaScript Date objects, <strong>DateTime strings are sufficient for instantiating them</strong>. JavaScript’s Date constructor is very flexible:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// ASP.NET AJAX form</span>
<span style="color: #003366; font-weight: bold;">var</span> foo <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1240718400000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// DateTime.ToLongDateString() form</span>
<span style="color: #003366; font-weight: bold;">var</span> bar <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Sunday, April 26, 2009'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// DateTime.ToShortDateString() form</span>
<span style="color: #003366; font-weight: bold;">var</span> baz <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'4/26/2009'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// true!</span>
foo <span style="color: #339933;">===</span> bar <span style="color: #339933;">===</span> baz<span style="color: #339933;">;</span></pre></div></div>

<p>By delaying string-to-Date conversions until truly necessary, we save effort on the server- and client-side. Not only that, but we have the option of retaining both the formatted string <em>and</em> the JavaScript Date to use as desired.</p>
<p>The best of both worlds.</p>
<p><hr />

<p>You've been reading <a href="http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/">How I handle JSON dates returned by ASP.NET AJAX</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p></p>


<p>Related posts:<ol><li><a href='http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/' rel='bookmark' title='Permanent Link: A breaking change between versions of ASP.NET AJAX'>A breaking change between versions of ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/' rel='bookmark' title='Permanent Link: 3 mistakes to avoid when using jQuery with ASP.NET AJAX'>3 mistakes to avoid when using jQuery with ASP.NET AJAX</a></li>
<li><a href='http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Permanent Link: Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
	</channel>
</rss>
