<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Simon Ince's Blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/simonince/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/simonince/feed.xml</link>
    <description>Ramblings of a gadget freak</description>
    <lastBuildDate>Sun, 05 Apr 2015 16:54:01 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>I've changed role</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/ive-changed-role</link>
      <pubDate>Mon, 19 Nov 2012 11:52:28 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2012/11/19/ive-changed-role/</guid>
      <description><![CDATA[Well it's happened; a short while ago I left the UK PSfD (Premier Support for Developers) team for...]]></description>
      <content:encoded><![CDATA[<p>Well it's happened; a short while ago I left the UK PSfD (Premier Support for Developers) team for new horizons. I had an awesome time in that team, and learned a lot from some very clever people - so if you fancy it check out the Microsoft careers site as they're hiring at the moment!</p>
<p>So what am I doing now? I moved to the "Global Consumer ISV Team", which is part of DPE (our evangelist arm), but rather than being managed out of the UK I report into Microsoft Corp in the US via the Server and Tools business.&nbsp;</p>
<p>I am responsible for business development with the EMEA partners on an exclusive list of top consumer brands... so in practice that translates to working with these brands to identify mutually beneficial opportunities, projects, approaches, marketing, and networking that lead to their successful adoption of the Microsoft platform in key competitive arenas such as Phone, Tablet, and Cloud.</p>
<p>Bottom line? I'm playing with gadgets, talking to people, and sending emails, all with a focus on cool consumer-facing technology: pretty much what I love the most and do the best anyway. Keep in touch if you worked with me already, and say hello if I cross your path in my new role! Chances are I'll still blog once in a while, but that'll likely be on slightly different topics. Let's see what happens...</p>]]></content:encoded>
    </item>
    <item>
      <title>Injecting Custom HTML Attributes in ASP.NET MVC</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/injecting-custom-html-attributes-in-asp-net-mvc</link>
      <pubDate>Thu, 24 May 2012 07:03:23 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2012/05/24/injecting-custom-html-attributes-in-asp-net-mvc/</guid>
      <description><![CDATA[Recently Stuart Leeks and I have developed a worrying pattern of having the same ideas at the same...]]></description>
      <content:encoded><![CDATA[<p><span style="font-family: Calibri; font-size: small;" face="Calibri" size="3">Recently </span><a href="http://blogs.msdn.com/stuartleeks"><span style="color: #0000ff; font-family: Calibri; font-size: small;" face="Calibri" size="3" color="#0000ff">Stuart Leeks</span></a><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri"> and I have developed a worrying pattern of having the same ideas at the same time. I&rsquo;m starting to doubt we&rsquo;re different people. Except he&rsquo;s about a foot taller so maybe that&rsquo;s aspirational from my side.</span></span></p>
<p><span style="font-family: Calibri; font-size: small;" face="Calibri" size="3">Our latest coinciding of ideas was a way to automatically inject HTML attributes for fields rendered as part of your model with Html.EditorFor. We&rsquo;ve just blogged about it on our team blog &ndash; </span><a href="http://blogs.msdn.com/b/ukadc/archive/2012/05/24/asp-net-mvc-adding-html-attributes-in-templated-helpers-editorfor.aspx"><span style="color: #0000ff; font-family: Calibri; font-size: small;" face="Calibri" size="3" color="#0000ff">Adding Html Attributes in Templated Helpers</span></a><span style="font-family: Calibri; font-size: small;" face="Calibri" size="3">, published the code on the MSDN Code Gallery under </span><a href="http://code.msdn.microsoft.com/Code-for-UkadcHtmlAttribute-7cc49a05"><span style="color: #0000ff; font-family: Calibri; font-size: small;" face="Calibri" size="3" color="#0000ff">UkadcHtmlAttributeProvider</span></a><span style="font-family: Calibri; font-size: small;" face="Calibri" size="3">, and pushed a working version to </span><a href="http://www.nuget.org/packages/UkadcHtmlAttributeProvider"><span style="color: #0000ff; font-family: Calibri; font-size: small;" face="Calibri" size="3" color="#0000ff">NuGet under UkadcHtmlAttributeProvider</span></a><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">.</span></span></p>
<p><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">Have a read of the blog post to learn more. To try our solution just use the NuGet command;</span></span></p>
<p><span style="font-family: courier new,courier; font-size: small;" size="3">Install-Package UkadcHtmlAttributeProvider</span></p>
<p><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">A few examples of attribute provider delegate registrations are below. Do let us know if you like the approach!</span></span></p>
<p><b><i><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">Output the aria-required attribute for required fields;</span></span></i></b></p>
<p><span style="font-family: courier new,courier;">HtmlAttributeProvider.Register(</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp; metadata =&gt; metadata.IsRequired,</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp; "aria-required",</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp; "true");</span></p>
<p><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">This results in the following HTML for a string field;</span></span></p>
<p><span style="font-family: courier new,courier; font-size: small;" size="3">&lt;input aria-required="true" class="text-box single-line" &hellip; snip &hellip; /&gt;</span></p>
<p><b><i><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">Output an HTML 5 Custom Data Attribute (CDA) when the field contains a URL;</span></span></i></b></p>
<p><span style="font-family: courier new,courier;">HtmlAttributeProvider.Register(</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp; metadata =&gt; metadata.DataTypeName == "Url",</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp; "data-url",</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp; "true");</span></p>
<p>&nbsp;<span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">This results in the following HTML for a string field;</span></span></p>
<p><span style="font-family: courier new,courier; font-size: small;" size="3">&lt;input class="text-box single-line" data-url="true" &hellip; snip &hellip; /&gt;</span></p>
<p><b><i><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">Output the Square Root of a value of a number field as an HTML 5 CDA;</span></span></i></b></p>
<p><span style="font-family: courier new,courier;">HtmlAttributeProvider.Register((html, metadata) =&gt;</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; {</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (metadata.ModelType == typeof(Int32))</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return new[]</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;new KeyValuePair&lt;string, object&gt;(</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"data-sqroot-value",</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Math.Sqrt(</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Convert.ToDouble(metadata.Model)))</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; };</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return Enumerable.Empty&lt;KeyValuePair&lt;string, object&gt;&gt;();</span></p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; });</span></p>
<p>&nbsp;<span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">This results in the following HTML for an Integer field;</span></span></p>
<p><span style="font-family: courier new,courier; font-size: small;" size="3">&lt;input class="text-box single-line" data-sqroot-value="4.58257569495584" &hellip; snip&hellip; /&gt;</span></p>
<p><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri">OK so that last one is a bit arbitrary &ndash; but there&rsquo;s a huge amount you can do here. Think of tab indexes, URLs for Ajax callbacks, CSS classes&hellip; the list goes on.</span></span></p>
<p><span style="font-family: Calibri; font-size: small;" face="Calibri" size="3">Head over to the </span><a href="http://blogs.msdn.com/b/ukadc/archive/2012/05/24/asp-net-mvc-adding-html-attributes-in-templated-helpers-editorfor.aspx"><span style="color: #0000ff; font-family: Calibri; font-size: small;" face="Calibri" size="3" color="#0000ff">blog post</span></a><span style="font-family: Calibri; font-size: small;" face="Calibri" size="3"> to read about how it works. And check out </span><a href="http://blogs.msdn.com/b/stuartleeks/archive/2012/05/24/asp-net-mvc-supplying-html-attributes-with-editorfor.aspx"><span style="color: #0000ff; font-family: Calibri; font-size: small;" face="Calibri" size="3" color="#0000ff">Stu&rsquo;s follow-up post</span></a><span style="font-size: small;" size="3"><span style="font-family: Calibri;" face="Calibri"> on some good real examples.</span></span></p>]]></content:encoded>
    </item>
    <item>
      <title>Templated Razor Delegates combined with Partial Views</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/templated-razor-delegates-combined-with-partial-views</link>
      <pubDate>Thu, 26 Jan 2012 01:14:54 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2012/01/26/templated-razor-delegates-combined-with-partial-views/</guid>
      <description><![CDATA[I was with a customer in Germany this week, and just before I left one of the (rather talented I...]]></description>
      <content:encoded><![CDATA[<p>I was with a customer in Germany this week, and just before I left one of the (rather talented I might say) developers asked me about passing markup into an HtmlHelper extension. It turns out this is pretty easy, as covered by Phil Haack under <a href="http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx">Templated Razor Delegates</a>. However, I particularly like keeping my HTML markup in cshtml files. It’s just easier to maintain. So I combined Phil’s post with the use of a partial view. The nice simple HtmlHelper extension looks like this;</p>  <div class="csharpcode">   <pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">static</span> MvcHtmlString Region&lt;TModel&gt;( </pre>

  <pre><span class="lnum">   2:  </span>   <span class="kwrd">this</span> HtmlHelper&lt;TModel&gt; html, </pre>

  <pre class="alt"><span class="lnum">   3:  </span>   Func&lt;TModel, <span class="kwrd">object</span>&gt; content) </pre>

  <pre><span class="lnum">   4:  </span>{ </pre>

  <pre class="alt"><span class="lnum">   5:  </span>   var result = content(html.ViewData.Model); </pre>

  <pre><span class="lnum">   6:  </span>   <span class="kwrd">return</span> html.Partial(<span class="str">&quot;_Region&quot;</span>, result); </pre>

  <pre class="alt"><span class="lnum">   7:  </span>} </pre>
</div>


<p>This accepts a Func&lt;TModel, object&gt; which is the Templated Razor Delegate. This is quite simply a snippet of Razor syntax that is executed to return markup as “result”.</p>

<div class="csharpcode">
  <pre class="alt"><span class="lnum">   1:  </span>@Html.Region(@&lt;text&gt;@Model.WelcomeMessage&lt;/text&gt;)</pre>
</div>


<p>I’ve combined my HtmlHelper extension with a partial view named _Region, stored in the Shared folder;</p>

<div class="csharpcode">
  <pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">&lt;</span><span class="html">fieldset</span> <span class="attr">class</span><span class="kwrd">=&quot;demoregion&quot;</span><span class="kwrd">&gt;</span> </pre>

  <pre><span class="lnum">   2:  </span>    <span class="kwrd">&lt;</span><span class="html">legend</span><span class="kwrd">&gt;</span>A Region<span class="kwrd">&lt;/</span><span class="html">legend</span><span class="kwrd">&gt;</span> </pre>

  <pre class="alt"><span class="lnum">   3:  </span>    <span class="kwrd">&lt;</span><span class="html">div</span><span class="kwrd">&gt;</span> </pre>

  <pre><span class="lnum">   4:  </span>        @Model </pre>

  <pre class="alt"><span class="lnum">   5:  </span>    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span> </pre>

  <pre><span class="lnum">   6:  </span><span class="kwrd">&lt;/</span><span class="html">fieldset</span><span class="kwrd">&gt;</span></pre>
</div>


<p>This would be way neater if I could use an @helper under App_Code, but in MVC 3 that feature doesn’t support using HtmlHelper, so you couldn’t use Html.Textbox in the template, for example.</p>

<p>The code is attached – easy huh?</p>

<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:3b19093f-2dac-45b3-9ad1-95c76568958f" class="wlWriterEditableSmartContent"><p><div><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/92/65/metablogapi/3821.EmbeddedContent_1.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-92-65-metablogapi/3821.EmbeddedContent_5F00_1.zip" target="_self">EmbeddedContent.zip</a></div></p></div>]]></content:encoded>
    </item>
    <item>
      <title>Mvc.ValidationTookit Alpha Release: Conditional Validation with MVC 3</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/mvc-validationtookit-alpha-release-conditional-validation-with-mvc-3</link>
      <pubDate>Thu, 29 Sep 2011 00:28:00 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2011/09/29/mvc-validationtookit-alpha-release-conditional-validation-with-mvc-3/</guid>
      <description><![CDATA[Update: I've not forgotten about this everyone, apologies for the delay. My attempt to get approval...]]></description>
      <content:encoded><![CDATA[<p><em><strong>Update</strong>: I've not forgotten about this everyone, apologies for the delay. My attempt to get approval to publish failed due to vacations (mine and others) so as soon as I can I'll try again. </em></p>
<p><em></em></p>
<p>My blog posts on doing conditional validation in MVC have always been popular, and I&rsquo;m frequently surprised by where I find that code &ndash; customers often say to me &ldquo;we found some guys blog with some code to do the validation we needed&rdquo; and sure enough it usually turns out to be mine!</p>
<p>There are two problems though &ndash; firstly, my code was always intended to be a sample to get you started, and that meant I&rsquo;d not written a comprehensive set of tests. Secondly, there are all sorts of validation cases that developers need that I hadn&rsquo;t covered.</p>
<p>So I decided to refresh the code base, both with additional validators and with a pretty decent set of tests. The first Alpha (i.e. incomplete, probably buggy, etc, etc you have been warned <img style="border-style: none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/92/65/metablogapi/6811.wlEmoticon-smile_2.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-92-65-metablogapi/6811.wlEmoticon_2D00_smile_5F00_2.png" />) release of this code is attached to this blog post.</p>
<h2>What&rsquo;s in the box?</h2>
<p>There are four main topics included in the box;</p>
<ul>
<li>Conditional required validation. This is the most common requirement, and is often used for forms that have optional sections.
<ul>
<li>RequiredIfAttribute. This attribute says &ldquo;this field is required if some other field has value X&rdquo;. It is used as [RequiredIf(&ldquo;OtherField&rdquo;, &ldquo;TargetValue&rdquo;)]</li>
<li>RequiredEmptyIfAttribute. This attribute says &ldquo;this field must be empty if some other field has value X&rdquo;. It is used as [RequiredEmptyIf(&ldquo;OtherField&rdquo;, &ldquo;TargetValue&rdquo;)]</li>
<li>conditional-validation.js &ndash; a JavaScript file to does the above in the browser to match the server-side implementation</li>
</ul>
</li>
<li>Dependency validation. Sometimes the value of one field depends on another.
<ul>
<li>RangeDefinedByFieldsAttribute. This states &ldquo;this field must be between the values in X field and Y field&rdquo;. It is used as [RangeDefinedByFields(typeof(Int32), &ldquo;MinField&rdquo;, &ldquo;MaxField&rdquo;)].</li>
<li>There is also script in conditional-validation.js to do this in the browser.</li>
</ul>
</li>
<li>Validation groups. Sometimes a field is only relevant if the user clicks one of the buttons available; perhaps if they click Delete none of the edited fields must be entered.
<ul>
<li>RequiredForButtonAttribute. This states &ldquo;the field is required if they user clicks button X&rdquo;. It is used as [RequiredForButton(&ldquo;ValidationGroupName&rdquo;, &ldquo;ButtonName&rdquo;)]</li>
<li>RequiredEmptyForButtonAttribute. OK, you probably get the point now. I&rsquo;ll let you infer what this does!</li>
<li>Html.SubmitForValidationGroup. To &ldquo;play nice&rdquo; with the RequiredForButtonAttribute and RequiredEmptyForButtonAttribute we need to ensure the buttons are created correctly, and we need a hidden field. This HtmlHelper extension handles this for us, and takes the form Html.SubmitForValidationGroup(&ldquo;ValidationGroupName&rdquo;, &ldquo;ButtonName&rdquo;)]</li>
<li>validation-groups.js &ndash; This JavaScript ensures that client-side validation groups work as well as server-side.</li>
</ul>
</li>
</ul>
<p>Note that all of these pieces work both server-side and client-side (in the browser) if you use the JavaScript included in /Mvc.ValidationToolkit.Harness/Scripts/MvcValidationToolkit/*.js.</p>
<p>Also, note that they all have MSTest unit tests and automated WaTiN UI tests that exercise both the JavaScript and Server implementations of each feature. I&rsquo;m positive it needs more tests (for example different data types).</p>
<h2>What do I need from you?</h2>
<p>I must emphasise that this release is a preview. So what next? Well I want to know a few things;</p>
<ol>
<li>What do you think? Is this useful?</li>
<li>What validators are missing?</li>
<li>What bugs have you found?</li>
<li>What testing priorities are there?</li>
</ol>
<p>Please comment on this post if you&rsquo;ve answers to those questions. But I also want to know <em>where this should live and how it should move forwards</em>. I would consider setting up a codeplex project if there were a few strong MVC &amp; jQuery developers that wanted to add to and evolve the library. Or is this drop enough to get you started? Let me know your thoughts.</p>
<p>In the mean time, I may blog on using the attributes a little more if I get the chance.</p>
<h2>Go Get It</h2>
<p>To have a look at the code, download the attachment to this post and have a look in Readme.txt &ndash; the only thing you need to do is grab a couple of NuGet packages and everything should work. Note: if you&rsquo;re running the WaTiN tests, run Visual Studio as elevated else you&rsquo;ll just get timeouts.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/21/80/07/Mvc.ValidationToolkit.Alpha.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-21-80-07/Mvc.ValidationToolkit.Alpha.zip">Mvc.ValidationToolkit.Alpha.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Immersive MVC and jQuery: Project Silk</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/immersive-mvc-and-jquery-project-silk</link>
      <pubDate>Mon, 26 Sep 2011 04:21:39 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2011/09/26/immersive-mvc-and-jquery-project-silk/</guid>
      <description><![CDATA[Patterns and Practices have just released their latest round of guidance for developing web...]]></description>
      <content:encoded><![CDATA[<p>Patterns and Practices have just released their latest round of guidance for developing web applications - “Project Silk”. I’ve been watching what they generate closely and I think you’ll be impressed. To quote the landing page;</p>  <p><em>“Project Silk provides guidance for building maintainable cross-browser web applications that are characterized by an intentional design, <strong>rich</strong> interactivity, and a <strong>responsive user interface</strong> (UI), resulting in an <strong>immersive</strong> and <strong>engaging</strong> user experience (UX). Such applications take advantage of the latest web standards, including HTML5, CSS3, and ECMAScript version 5, and modern web technologies such as jQuery and ASP.NET MVC3“</em></p>  <p>The highlights are mine -&#160; because it is key to understand that this guidance isn’t just about code structure and separation of concerns, but also covers making your UI really sing. Check out the guidance here;</p>  <p>&#160;</p>  <p>Landing Page:</p>  <p><a title="http://msdn.microsoft.com/en-us/library/hh396380.aspx" href="http://msdn.microsoft.com/en-us/library/hh396380.aspx">http://msdn.microsoft.com/en-us/library/hh396380.aspx</a></p>  <p>Roadmap to navigating the guidance:</p>  <p><a title="http://msdn.microsoft.com/en-us/library/hh404078.aspx" href="http://msdn.microsoft.com/en-us/library/hh404078.aspx">http://msdn.microsoft.com/en-us/library/hh404078.aspx</a></p>  <p>A video showcasing the output!</p>  <p><a title="https://channel9.msdn.com/posts/Project-Silk-Mileage-Stats-Application" href="https://channel9.msdn.com/posts/Project-Silk-Mileage-Stats-Application">https://channel9.msdn.com/posts/Project-Silk-Mileage-Stats-Application</a></p>  <p>&#160;</p>  <p>If you’re doing MVC and jQuery, you’ve got to check it out…</p>]]></content:encoded>
    </item>
    <item>
      <title>Project Silk: Patterns and Practices do Rich Web Apps</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/project-silk-patterns-and-practices-do-rich-web-apps</link>
      <pubDate>Wed, 11 May 2011 13:09:53 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2011/05/11/project-silk-patterns-and-practices-do-rich-web-apps/</guid>
      <description><![CDATA[My blog has been quiet of late – because our team is busy I think. We’re recruiting by the way...]]></description>
      <content:encoded><![CDATA[<p>My blog has been quiet of late – because our team is busy I think. We’re recruiting by the way <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/92/65/metablogapi/0654.wlEmoticon-smile_191AC275.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-92-65-metablogapi/0654.wlEmoticon_2D00_smile_5F00_191AC275.png" /></p>  <p>Something I’ve been wanting to blog about for a while now is “Project Silk”. This is Patterns &amp; Practices latest round of web development guidance. Karl Shifflett&#160; is the man at the wheel, so be sure to <a href="http://karlshifflett.wordpress.com/">check out his blog</a>. Silk is all about getting the structure of both server-side and script code right, and building truly outstanding interactive user interfaces with the latest and greatest tools on the Microsoft platform. That means they’re using MVC 3 and jQuery to create an appealing and enjoyable experience when using the fully complete Reference Implementation they’ve built… I think it looks great.</p>  <p>I hope to blog more on some of the detail of what they’ve been working on soon, but don’t wait for me – go check it out on codeplex here; <a href="http://silk.codeplex.com/">Project Silk</a></p>  <p>Much of the work has gone into building jQuery UI “widgets”, and the guidance includes lessons they’ve learned from strapping all this together. The documentation is currently being reviewed so if you fancy having a read of the drafts that have been published head over to codeplex.</p>]]></content:encoded>
    </item>
    <item>
      <title>JavaScript Architecture</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/javascript-architecture</link>
      <pubDate>Mon, 28 Feb 2011 12:34:58 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2011/02/28/javascript-architecture/</guid>
      <description><![CDATA[No, that isn’t meant to be an oxymoron. But something I’ve noticed recently is that people’s...]]></description>
      <content:encoded><![CDATA[<p>No, that isn’t meant to be an oxymoron. But something I’ve noticed recently is that people’s approach to JavaScript seems to be diverging down two common paths. This blog post is designed to encourage you to adopt the one you probably aren’t planning to adopt right now! The approaches I’m describing are depicted below;</p>  <p><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/92/65/7851.JavaScriptArch.jpg" original-url="http://blogs.msdn.com/cfs-filesystemfile.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-92-65/7851.JavaScriptArch.jpg" /></p>  <p>Keep that in mind and we’ll look at each in turn…</p>  <h2>Script-on-top</h2>  <p>What I’ve dubbed “script-on-top” is what I believe most developers do right now. That is, they look to sit JavaScript on top of the HTML and CSS; the script uses the HTML and CSS and manipulates them as though they are components just waiting to be orchestrated. You’ll often see code that looks a bit like this (I’m using jQuery);</p>  <div class="csharpcode">   <pre class="alt"><span class="lnum">   1:  </span>$(document).ready(function () {</pre>

  <pre><span class="lnum">   2:  </span>    $(<span class="str">'#combo'</span>).change(function () {</pre>

  <pre class="alt"><span class="lnum">   3:  </span>        var <span class="kwrd">value</span> = $(<span class="kwrd">this</span>).val();</pre>

  <pre><span class="lnum">   4:  </span>        var result = myframework.getDisplayMessageFromServer(<span class="kwrd">value</span>);</pre>

  <pre class="alt"><span class="lnum">   5:  </span>        $(<span class="str">'#messagediv'</span>).html(result);</pre>

  <pre><span class="lnum">   6:  </span>    });</pre>

  <pre class="alt"><span class="lnum">   7:  </span>});</pre>
</div>


<p><em><font size="2">* Note that none of the script in this post is real. I just hacked it into notepad – but it demonstrates the point sufficiently.</font></em></p>

<p>There are some good practices there – not least the fact that the call back to the server is encapsulated within a reusable framework. This is layering, effectively creating a data access layer in JavaScript, and hence is following patterns that have been established for a long time for server-side code. The configuration for how to communicate with the server and the location of the server endpoint is all encapsulated within this framework.</p>

<p>However, I have a few problems with this approach.</p>

<p>1. I don’t like specifying element identifiers in JavaScript. Why? Because it <em>feels wrong</em>. It just does. Stick with me and you might start to agree. Fundamentally this comes down to the separation of concerns between CSS, HTML, and JavaScript.</p>

<p>2. If I have lots of drop-down lists that have very similar behaviour, I still have to wire up every single one. A lot of developers really do wire up every single one manually in code like that above. There are ways to apply behaviour in a blanket manner but none quite so good as my preferred approach… so hold that thought.</p>

<p>3. I don’t like the idea of having to write an entirely new User Interface “manager” component of some description. What often happens with the above approach is that when a page gets more complex developers create a central class that wires up all these events, maybe caches some data, and more. Why? Surely we’re done all that server-side, must I really Repeat myself (R capitalised in homage to DRY) on the client?</p>

<p>4. The URLs to each endpoint are embedded in the framework. But my URLs are “designed” on the server (especially if you’re using Routing, perhaps with ASP.NET MVC)… surely I don’t want to hard-code them in the script too?</p>

<h2>Script-as-a-platform</h2>

<p>So what is the alternative? I believe we need to turn our way of thinking about JavaScript on it’s head. Instead, think of CSS and JavaScript as <strong>defining a platform</strong> that our HTML mark-up simply refers to in order to build up a user interface. Rather than our JavaScript taking ownership of HTML elements, our HTML makes use of predefined JavaScript “behaviours” (yes, I know that is an emotive term for JavaScript so forgive me!) and CSS styles. </p>

<p>Such a mind-set leads to HTML that looks like this (I’m using ASP.NET MVC 3 with a Razor view);</p>

<div class="csharpcode">
  <pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">&lt;</span><span class="html">select</span> </pre>

  <pre><span class="lnum">   2:  </span>    <span class="attr">data-getmessage-output</span><span class="kwrd">=&quot;#messagediv&quot;</span> </pre>

  <pre class="alt"><span class="lnum">   3:  </span>    <span class="attr">data-getmessage-source</span><span class="kwrd">=&quot;@Url.Action(&quot;</span><span class="attr">Message</span><span class="kwrd">&quot;, &quot;</span><span class="attr">Ajax</span><span class="kwrd">&quot;, new { item = &quot;</span>{<span class="attr">placeholder</span>}<span class="kwrd">&quot; })&quot;</span><span class="kwrd">&gt;</span></pre>

  <pre><span class="lnum">   4:  </span><span class="kwrd">&lt;/</span><span class="html">select</span><span class="kwrd">&gt;</span></pre>

  <pre class="alt"><span class="lnum">   5:  </span>&#160;</pre>

  <pre><span class="lnum">   6:  </span><span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">id</span><span class="kwrd">=&quot;messagediv&quot;</span><span class="kwrd">&gt;&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>


<p>… and matching JavaScript a bit like this;</p>

<div class="csharpcode">
  <pre class="alt"><span class="lnum">   1:  </span>$(document).ready(<span class="kwrd">function</span> () {</pre>

  <pre><span class="lnum">   2:  </span>    $(<span class="str">'*[data-getmessage-source]'</span>).change(<span class="kwrd">function</span> () {</pre>

  <pre class="alt"><span class="lnum">   3:  </span>        <span class="kwrd">var</span> value = $(<span class="kwrd">this</span>).val();</pre>

  <pre><span class="lnum">   4:  </span>        <span class="kwrd">var</span> url = $(<span class="kwrd">this</span>)</pre>

  <pre class="alt"><span class="lnum">   5:  </span>            .data(<span class="str">'getmessage-source'</span>)</pre>

  <pre><span class="lnum">   6:  </span>            .replace(<span class="str">'{placeholder}'</span>, value); ;</pre>

  <pre class="alt"><span class="lnum">   7:  </span>        <span class="kwrd">var</span> output = $(<span class="kwrd">this</span>).data(<span class="str">'getmessage-output'</span>);</pre>

  <pre><span class="lnum">   8:  </span>        <span class="kwrd">var</span> result = myframework.getDataFromServer(url);</pre>

  <pre class="alt"><span class="lnum">   9:  </span>        $(output).html(result);</pre>

  <pre><span class="lnum">  10:  </span>    });</pre>

  <pre class="alt"><span class="lnum">  11:  </span>});</pre>
</div>


<p>So what is the difference? The difference is that my JavaScript is a reusable component, and my HTML has output instructions to the client to make use of that component through the use of an HTML 5 Custom Data Attribute. It could easily have used a CSS class instead if the parameters to my component were simpler. The script is slightly longer, but it isn’t complex – and none of it will be repeated in individual pages.</p>

<p>As a result, the URL to the endpoint is no longer hard-coded in a JavaScript library. And all SELECTs that should have this behaviour get it automatically just by referencing this script. The pairing of output DIV and drop-down list is clearly defined in HTML, not tucked away in JavaScript somewhere. There are, in fact, no IDs in my JavaScript, which means that my HTML is completely owning the document structure while JavaScript provides behaviour for that structure... without detailed knowledge of it.</p>

<p>I can still create reusable JavaScript – in fact, my sample code could be hugely refactored into something much more reusable. </p>

<p>But most of all, there is no longer a need or temptation for a central orchestrating JavaScript component – our orchestrating is done by the HTML, which is generated server-side, so our server code is really pulling the strings. We’ve moved our mind-set from writing JavaScript to “make the UI work” into <strong><u>writing HTML that composes reusable JavaScript components and behaviours</u></strong>. The highlight is because I believe that’s a good summary description of what I’d encourage you to do.</p>

<h2>Does It Matter?</h2>

<p>Yes, I believe it does. Follow this composition approach and your JavaScript code will be easier to thoroughly test (because you won’t have lots of separate wiring up code for each page), and the act of composing will often feel simpler to the developer than writing imperative code to “pull strings” for any particular page.</p>

<p>So, what do <u>you</u> think?</p>]]></content:encoded>
    </item>
    <item>
      <title>What’s My Day Job?</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/whats-my-day-job</link>
      <pubDate>Thu, 17 Feb 2011 07:55:56 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2011/02/17/whats-my-day-job/</guid>
      <description><![CDATA[If you’re wondering what it is I do all day, the UK TechNet Blog have just published an interview...]]></description>
      <content:encoded><![CDATA[<p>If you’re wondering what it is I do all day, the UK TechNet Blog have just <a href="http://blogs.technet.com/b/uktechnet/archive/2011/02/17/a-day-in-the-life-of-simon-ince-application-development-manager.aspx">published an interview</a> with me as part of their “day in the life” series, which looks at the various technical roles within Microsoft UK. Be sure to check the others out too!</p>  <p>On a related note, if you’re curious about my role in particular then check out my team’s blog series of “<a href="http://blogs.msdn.com/b/ukadc/archive/tags/interview/">Meet an ADC</a>”; mine is <a href="http://blogs.msdn.com/b/ukadc/archive/2008/11/03/meet-simon-ince-he-s-an-adc.aspx">here</a>. Our job title changed from Application Development Consultant (ADC) to Application Development Manager (ADM) so the acronym may be slightly different but the facts are still the same.</p>]]></content:encoded>
    </item>
    <item>
      <title>Detecting which button was clicked in MVC</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/detecting-which-button-was-clicked-in-mvc</link>
      <pubDate>Sat, 12 Feb 2011 09:52:46 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2011/02/12/detecting-which-button-was-clicked-in-mvc/</guid>
      <description><![CDATA[I’ve seen a few hacks in the past to try and work out which button caused a form POST in ASP.NET...]]></description>
      <content:encoded><![CDATA[<p>I’ve seen a few hacks in the past to try and work out which button caused a form POST in ASP.NET MVC, but the truth is it is pretty easy.</p>  <p><strong>Step 1</strong>: Inside your form, add two Submit buttons. Add a name attribute to both (note it isn’t added by MVC by default);</p>  <div class="csharpcode">   <pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">&lt;</span><span class="html">p</span><span class="kwrd">&gt;</span></pre>

  <pre><span class="lnum">   2:  </span>    <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">type</span><span class="kwrd">=&quot;submit&quot;</span> <span class="attr">name</span><span class="kwrd">=&quot;Command&quot;</span> <span class="attr">value</span><span class="kwrd">=&quot;Save&quot;</span> <span class="kwrd">/&gt;</span></pre>

  <pre class="alt"><span class="lnum">   3:  </span>    <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">type</span><span class="kwrd">=&quot;submit&quot;</span> <span class="attr">name</span><span class="kwrd">=&quot;Command&quot;</span> <span class="attr">value</span><span class="kwrd">=&quot;Delete&quot;</span> <span class="kwrd">/&gt;</span></pre>

  <pre><span class="lnum">   4:  </span><span class="kwrd">&lt;/</span><span class="html">p</span><span class="kwrd">&gt;</span></pre>
</div>


<p>Note both have the same name.</p>

<p><strong>Step 2</strong>: Inside your action, add a parameter that matches the name of the buttons;</p>

<div class="csharpcode">
  <pre class="alt"><span class="lnum">   1:  </span>[HttpPost]</pre>

  <pre><span class="lnum">   2:  </span><span class="kwrd">public</span> ActionResult Index(</pre>

  <pre class="alt"><span class="lnum">   3:  </span>    Person person, </pre>

  <pre><span class="lnum">   4:  </span>    <span class="kwrd">string</span> command)</pre>

  <pre class="alt"><span class="lnum">   5:  </span>{</pre>

  <pre><span class="lnum">   6:  </span>    <span class="kwrd">bool</span> saved = (command == <span class="str">&quot;Save&quot;</span>);</pre>

  <pre class="alt"><span class="lnum">   7:  </span>&#160;</pre>

  <pre><span class="lnum">   8:  </span>    <span class="kwrd">if</span> (saved)</pre>

  <pre class="alt"><span class="lnum">   9:  </span>        <span class="rem">// code removed</span></pre>

  <pre><span class="lnum">  10:  </span>    <span class="kwrd">else</span></pre>

  <pre class="alt"><span class="lnum">  11:  </span>        <span class="rem">// code removed</span></pre>

  <pre><span class="lnum">  12:  </span>}</pre>
</div>


<p>Simple huh? You could write some clever extension method to inspect the posted HTTP values, but I find this approach far more elegant. It is really clear that I’m expecting the “command” to be posted to my action.</p>

<p>A part of me wonders if naming all your buttons the same contravenes the HTML specification, but I can find no evidence of this – it is an accepted practice for checkboxes and radio buttons of course, and I’ve found this to work well. If you know otherwise do shout up. Like it? Hate it?</p>

<p><strong>Step 3</strong>: Well… let’s take it one step further and create an enum of commands;</p>

<div class="csharpcode">
  <pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">enum</span> Command</pre>

  <pre><span class="lnum">   2:  </span>{</pre>

  <pre class="alt"><span class="lnum">   3:  </span>    Save,</pre>

  <pre><span class="lnum">   4:  </span>    Delete</pre>

  <pre class="alt"><span class="lnum">   5:  </span>}</pre>
</div>


<p><strong>Step 4</strong>: … and update our action method parameter’s type to be our new enum, and of course our logic to use it;</p>

<div class="csharpcode">
  <pre class="alt"><span class="lnum">   1:  </span>[HttpPost]</pre>

  <pre><span class="lnum">   2:  </span><span class="kwrd">public</span> ActionResult Index(</pre>

  <pre class="alt"><span class="lnum">   3:  </span>    Person person, </pre>

  <pre><span class="lnum">   4:  </span>    Command command)</pre>

  <pre class="alt"><span class="lnum">   5:  </span>{</pre>

  <pre><span class="lnum">   6:  </span>    <span class="kwrd">if</span> (command == Command.Save)</pre>

  <pre class="alt"><span class="lnum">   7:  </span>        <span class="rem">// code removed</span></pre>

  <pre><span class="lnum">   8:  </span>    <span class="kwrd">else</span></pre>

  <pre class="alt"><span class="lnum">   9:  </span>        <span class="rem">// code removed</span></pre>

  <pre><span class="lnum">  10:  </span>}</pre>
</div>


<p>Hey presto! Strongly typed clear code that reacts to which button was clicked.</p>]]></content:encoded>
    </item>
    <item>
      <title>Conditional Validation in ASP.NET MVC 3</title>
      <link>https://docs.microsoft.com/archive/blogs/simonince/conditional-validation-in-asp-net-mvc-3</link>
      <pubDate>Fri, 04 Feb 2011 11:37:00 GMT</pubDate>
      <dc:creator><![CDATA[Simon J Ince]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/simonince/2011/02/04/conditional-validation-in-asp-net-mvc-3/</guid>
      <description><![CDATA[Update: If you like this, you'll like Mvc.ValidationTookit even more - check out this post!
Some...]]></description>
      <content:encoded><![CDATA[<p><span style="font-size: medium;"><strong>Update: If you like this, you'll like Mvc.ValidationTookit even more - check out <a title="this post" href="http://blogs.msdn.com/b/simonince/archive/2011/09/29/mvc-validationtookit-alpha-release-conditional-validation-with-mvc-3.aspx">this post</a>!</strong></span></p>
<p>Some time ago I blogged on <a href="http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx">Conditional Validation in MVC</a>, and <a href="http://blogs.msdn.com/b/simonince/archive/2010/06/11/adding-client-side-script-to-an-mvc-conditional-validator.aspx">Adding Client-Side Script to an MVC Conditional Validator</a>. A number of people have asked me to update the sample to MVC 3, so guess what &ndash; it&rsquo;s your birthday! The main differences are summarised below&hellip; and check out the code download to see it working. I&rsquo;d recommend reading my previous two posts if you want the background on how it all works.</p>
<p><strong>Important</strong>: Note that this is by no means a complete solution, and neither were my previous ones. They&rsquo;re POCs intended to get you started! For example, you may need to handle different data types (Int32, perhaps) or control types (radio buttons, perhaps) yourself. I&rsquo;d also recommend thoroughly testing the code. Enjoy&hellip;</p>
<h2>The Attribute is the Adapter!</h2>
<p>Hooray! There&rsquo;s no need for an adapter class anymore. The Attribute instead can implement an interface;</p>
<div class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span><span class="kwrd">public</span> <span class="kwrd">class</span> RequiredIfAttribute : ValidationAttribute, IClientValidatable</pre>
<pre><span class="lnum"> 2: </span>{</pre>
<pre class="alt"><span class="lnum"> 3: </span>}</pre>
</div>
<p>IClientValidatable demands that we implement GetClientValidationRules on our Attribute, in a very similar way to the example in my previous posts. That&rsquo;s much neater.</p>
<h2>Our Context is Different</h2>
<p>I&rsquo;m not particularly happy with this workaround right now, so if you&rsquo;ve a better solution let me know. The issue is that when we are emitting the Client Validation Rules described above, we must calculate the Identifier that the control we depend upon will have when it is written out into the HTML. To do this, we call;</p>
<div class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span><span class="kwrd">string</span> depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(<span class="kwrd">this</span>.DependentProperty);</pre>
</div>
<p>However&hellip; now that this method is being called from within the Attribute itself, rather than within an Adapter, that means it is executed while the field the Attribute applies to is being rendered. That means the context is one level lower than it was for my original solution. MVC tracks a &ldquo;stack&rdquo; of field prefixes in this context whilst rendering fields, and each time it ducks into a new template it adds a prefix. So when rendering our Person entity (which is a variable called model for example) the prefix would be &ldquo;model_&rdquo;. When rendering Person&rsquo;s Name, it would be &ldquo;model_Name&rdquo;. And if we had an address field on Person, that in turn had a City field, it could become &ldquo;model_Address_City&rdquo;. Note the &ldquo;model_&rdquo; bit often isn&rsquo;t there &ndash; it depends, and I&rsquo;m simplifying <img style="border-style: none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/92/65/metablogapi/0513.wlEmoticon-smile_0DC82D71.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-92-65-metablogapi/0513.wlEmoticon_2D00_smile_5F00_0DC82D71.png" /></p>
<p>What this means is that when calculating the dependent property ID with the code above, this context is &ldquo;City&rdquo; or &ldquo;Country&rdquo; (as the attribute is used on two fields it is called twice) rather than String.Empty. Which means it calculates the HTML ID of the &ldquo;IsUKResident&rdquo; field to be &ldquo;City_IsUKResident&rdquo;, instead of &ldquo;IsUKResident&rdquo;, and of course &ldquo;City_IsUKResident&rdquo; doesn&rsquo;t exist. Therefore I have to post-process it to strip off &ldquo;City_&rdquo;.</p>
<p>Yuck. Anyone know how to navigate the prefix hierarchy to stop this happening? It does seem to work though.</p>
<h2>jQuery Validation</h2>
<p>Next up, we use the jQuery.validate library to write our validation functions. This is now the only option, instead of one of two options as it was before. My validator looks like this;</p>
<div class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span>$.validator.addMethod(<span class="str">'requiredif'</span>,</pre>
<pre><span class="lnum"> 2: </span>    function (<span class="kwrd">value</span>, element, parameters) {</pre>
<pre class="alt"><span class="lnum"> 3: </span>        var id = <span class="str">'#'</span> + parameters[<span class="str">'dependentproperty'</span>];</pre>
<pre><span class="lnum"> 4: </span>&nbsp;</pre>
<pre class="alt"><span class="lnum"> 5: </span>        <span class="rem">// get the target value (as a string, </span></pre>
<pre><span class="lnum"> 6: </span>        <span class="rem">// as that's what actual value will be)</span></pre>
<pre class="alt"><span class="lnum"> 7: </span>        var targetvalue = parameters[<span class="str">'targetvalue'</span>];</pre>
<pre><span class="lnum"> 8: </span>        targetvalue = </pre>
<pre class="alt"><span class="lnum"> 9: </span>          (targetvalue == <span class="kwrd">null</span> ? <span class="str">''</span> : targetvalue).toString();</pre>
<pre><span class="lnum"> 10: </span>&nbsp;</pre>
<pre class="alt"><span class="lnum"> 11: </span>        <span class="rem">// get the actual value of the target control</span></pre>
<pre><span class="lnum"> 12: </span>        <span class="rem">// note - this probably needs to cater for more </span></pre>
<pre class="alt"><span class="lnum"> 13: </span>        <span class="rem">// control types, e.g. radios</span></pre>
<pre><span class="lnum"> 14: </span>        var control = $(id);</pre>
<pre class="alt"><span class="lnum"> 15: </span>        var controltype = control.attr(<span class="str">'type'</span>);</pre>
<pre><span class="lnum"> 16: </span>        var actualvalue =</pre>
<pre class="alt"><span class="lnum"> 17: </span>            controltype === <span class="str">'checkbox'</span> ?</pre>
<pre><span class="lnum"> 18: </span>            control.attr(<span class="str">'checked'</span>).toString() :</pre>
<pre class="alt"><span class="lnum"> 19: </span>            control.val();</pre>
<pre><span class="lnum"> 20: </span>&nbsp;</pre>
<pre class="alt"><span class="lnum"> 21: </span>        <span class="rem">// if the condition is true, reuse the existing </span></pre>
<pre><span class="lnum"> 22: </span>        <span class="rem">// required field validator functionality</span></pre>
<pre class="alt"><span class="lnum"> 23: </span>        <span class="kwrd">if</span> (targetvalue === actualvalue)</pre>
<pre><span class="lnum"> 24: </span>            <span class="kwrd">return</span> $.validator.methods.required.call(</pre>
<pre class="alt"><span class="lnum"> 25: </span>              <span class="kwrd">this</span>, <span class="kwrd">value</span>, element, parameters);</pre>
<pre><span class="lnum"> 26: </span>&nbsp;</pre>
<pre class="alt"><span class="lnum"> 27: </span>        <span class="kwrd">return</span> <span class="kwrd">true</span>;</pre>
<pre><span class="lnum"> 28: </span>    }</pre>
<pre class="alt"><span class="lnum"> 29: </span>);</pre>
</div>
<p>You can see I&rsquo;m just reusing the built in &ldquo;required&rdquo; validation if I determine it needs to be run.</p>
<p>However, we do also need to add an adapter that extracts the HTML 5 Custom Data Attributes that MVC adds to my input controls (use View Source and look for &ldquo;data-XXX&rdquo; on the &lt;input&gt; elements if you don&rsquo;t know what these are &ndash; or read my article <a href="http://blogs.msdn.com/b/simonince/archive/2011/01/14/unobtrusive-jquery-and-html-5-msdn-flash-article.aspx">here</a>) and passes them to my validation method. Mine looks like this;</p>
<div class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span>$.validator.unobtrusive.adapters.add(</pre>
<pre><span class="lnum"> 2: </span>    <span class="str">'requiredif'</span>, </pre>
<pre class="alt"><span class="lnum"> 3: </span>    [<span class="str">'dependentproperty'</span>, <span class="str">'targetvalue'</span>], </pre>
<pre><span class="lnum"> 4: </span>    function (options) {</pre>
<pre class="alt"><span class="lnum"> 5: </span>        options.rules[<span class="str">'requiredif'</span>] = {</pre>
<pre><span class="lnum"> 6: </span>            dependentproperty: options.<span class="kwrd">params</span>[<span class="str">'dependentproperty'</span>],</pre>
<pre class="alt"><span class="lnum"> 7: </span>            targetvalue: options.<span class="kwrd">params</span>[<span class="str">'targetvalue'</span>]</pre>
<pre><span class="lnum"> 8: </span>        };</pre>
<pre class="alt"><span class="lnum"> 9: </span>        options.messages[<span class="str">'requiredif'</span>] = options.message;</pre>
<pre><span class="lnum"> 10: </span>    });</pre>
</div>
<p>This states that I require two parameters &ndash; dependentproperty and targetvalue. These are therefore passed in the options object for me. I must then do any processing on them that is required (none, in this case) and create an entry in options.rules with their processed values. I also need to ensure I put the error message into a dictionary indexed by the name of my validation rule. Phew! I&rsquo;m sure that could be easier, couldn&rsquo;t it? Perhaps I&rsquo;ll write a little helper&hellip; there are helper functions for rules that only have a single parameter or need a boolean, but mine didn&rsquo;t fit that pattern.</p>
<h2>Enabling Validation</h2>
<p>&hellip; is no longer required in the View, because it is enabled in Web.config instead, and is set to &ldquo;true&rdquo; by default! Excellent news!</p>
<h2>Conclusion</h2>
<p>Well, I hope that has been pleasantly brief. Download the code and have a play if you&rsquo;re interested, and let me know how you get on. I think MVC 3 is a giant leap towards far better validation&hellip; and to celebrate that the sample uses Razor, of course!</p>
<div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:018766d7-fad8-443b-9a75-a549d48529cb" class="wlWriterEditableSmartContent">
<div><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/92/65/metablogapi/5327.Mvc3ConditionalValidation_5E9641D9.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-92-65-metablogapi/5327.Mvc3ConditionalValidation_5F00_5E9641D9.zip" target="_self">Mvc3ConditionalValidation.zip</a></div>
</div>]]></content:encoded>
    </item>
  </channel>
</rss>