<?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>devermind.com</title>
	<atom:link href="http://devermind.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://devermind.com</link>
	<description>Adrian Grigore's software development weblog. Motto: I will not waste my time looking for a clever motto.</description>
	<lastBuildDate>Sat, 07 Aug 2010 07:03:53 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>jQuery Selectmenu widget for jquery-ui 1.8</title>
		<link>http://devermind.com/aspnet/jquery-selectmenu-widget-for-jquery-ui-1-8/</link>
		<comments>http://devermind.com/aspnet/jquery-selectmenu-widget-for-jquery-ui-1-8/#comments</comments>
		<pubDate>Tue, 11 May 2010 09:17:14 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://devermind.com/aspnet/jquery-selectmenu-widget-for-jquery-ui-1-8/</guid>
		<description><![CDATA[My current web project includes some &#60;select&#62; elements with &#60;group&#62; children to represent projects belonging to certain customers.
Unfortunately there is no way  to style native &#60;select&#62; elements and Firefox lacks proper indentation for the &#60;option&#62; elements belonging to groups. This leads to a very confusing layout:

So I used the jQuery.Selectmenu plugin to style the &#60;select&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>My current web project includes some &lt;select&gt; elements with &lt;group&gt; children to represent projects belonging to certain customers.</p>
<p>Unfortunately there is no way  to style native &lt;select&gt; elements and Firefox lacks proper indentation for the &lt;option&gt; elements belonging to groups. This leads to a very confusing layout:</p>
<p><a href="http://devermind.com/wp-content/uploads/2010/05/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://devermind.com/wp-content/uploads/2010/05/image_thumb.png" border="0" alt="image" width="240" height="244" /></a></p>
<p>So I used the jQuery.Selectmenu plugin to style the &lt;select&gt; elements in a clean and consistent way across all browsers:</p>
<p><a href="http://devermind.com/wp-content/uploads/2010/05/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://devermind.com/wp-content/uploads/2010/05/image_thumb1.png" border="0" alt="image" width="244" height="196" /></a></p>
<p>Unfortunately the plugin does not seem to be maintained by the jquery.ui group anymore. I made a few minor changes to the plugin so that it works with jquery.ui 1.8 and properly displays groups with space characters.</p>
<p>The plugin is no longer maintained on the jquery.ui wiki, so I am simply uploading my version here:</p>
<div id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:cb6fba35-b7c6-4468-906d-66d871482b97" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<div><a href="http://devermind.com/wp-content/uploads/2010/05/jqueryuiselectmenu3.zip" target="_self">jquery-ui-selectmenu.zip</a></div>
<div></div>
<div><strong>Edit : </strong><a title="Felix Nagel" href="http://www.felixnagel.com/blog/">Felix Nagel</a> has created a github branch for the plugin based on my version. He intends to keep maintaining the plugin, so for a more mature version visit his <a href="http://github.com/fnagel/jquery-ui/tree/selectmenu/">jquery-selectmenu github repository branch</a> and get the plugin from there.</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet/jquery-selectmenu-widget-for-jquery-ui-1-8/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>User Interface Testing with Selenium Vs. Coded UI</title>
		<link>http://devermind.com/testing/selenium-vs-coded-ui-my-perspective/</link>
		<comments>http://devermind.com/testing/selenium-vs-coded-ui-my-perspective/#comments</comments>
		<pubDate>Thu, 06 May 2010 19:06:08 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[codedui selenium testing test]]></category>

		<guid isPermaLink="false">http://devermind.com/testing/selenium-vs-coded-ui-my-perspective/</guid>
		<description><![CDATA[This week I needed to write some automated UI level tests for my current web project (LogMyTime Zeiterfassung). After a bit of research, I narrowed the list of candidates down to Selenium and Visual Studio UI Automation testing (a.k.a. Coded UI). Then I spent a couple of hours with each tool to see what works [...]]]></description>
			<content:encoded><![CDATA[<p>This week I needed to write some automated UI level tests for my current web project (<a href="http://www.logmytime.de">LogMyTime Zeiterfassung</a>). After a bit of research, I narrowed the list of candidates down to <a href="http://seleniumhq.org/">Selenium</a> and Visual Studio UI Automation testing (a.k.a. <a href="http://social.msdn.microsoft.com/Forums/de-CH/vsautotest/threads">Coded UI</a>). Then I spent a couple of hours with each tool to see what works better for me.</p>
<p>So here’s my first impression:</p>
<h2>Selenium</h2>
<p>Selenium consists of an IDE that comes as a Firefox Add-On, a remote control for automated playback of tests and Selenium Grid, which is used for distributing tests across multiple servers.</p>
<p>This is what I found out after two hours of playing with the Selenium IDE:</p>
<p><strong>The Good:</strong></p>
<ul>
<li>Very easy to get your first tests running. </li>
<li>Highly intuitive interface, at least when it’s working properly. </li>
<li>Good workflow since the IDE is visible side-by-side with your browser. </li>
<li>Inline help shown inside the IDE for quick reference </li>
<li>Generated source code (html) is very small and easily readable </li>
<li>Tests can be exported in many different programming languages </li>
<li>Test recording and playback is very fast. </li>
<li>Easy to extend with custom actions and assertions </li>
</ul>
<p><strong>The Bad:</strong></p>
<ul>
<li>Extremely buggy IDE. Within about two hours of usage I lost some test cases, saw some exceptions and noticed some problems with the source code export feature. </li>
<li><strike>Re-use of recurring test steps and assertions does not seem to be possible without custom coding and a lot of copy and paste.</strike> <strong>Edit:</strong> I just found a workaround to this. See Edit1 below the article.</li>
<li>Simple assertions (such as check if a given string is shown on the web page) can be added with a few mouse clicks. But more thorough tests such as “check if the string “foo” appears in a div with the ID “bar” require custom coding. </li>
<li>All custom code has to be written in JavaScript. Not a big issue, but I still prefer type-safe languages. </li>
<li>No out of the box support test setup routines. This again requires custom coding. </li>
</ul>
<h2>Coded UI</h2>
<p>Coded UI is a new addition to Visual Studio 2010. Tests can be recorded with the new MS Test manager (which I can’t use since it requires Team Foundation Server) or from within Visual Studio. Tests can be replayed from within Visual Studio, MS Test Manager or via command line on any Windows machine with an installed <a href="http://msdn.microsoft.com/en-us/library/dd648127.aspx">Test Agent</a>.</p>
<p>In contrast to Selenium, Coded UI can test many different flavors of user interfaces, such as MFC, WPF, Web apps and even Silverlight applications.</p>
<p>So here’s my first impression regarding Coded UI:</p>
<p><strong>The Good:</strong></p>
<ul>
<li>Everything seems very stable. </li>
<li>You can test many different kinds of user interfaces, not just he web. </li>
<li>Frequently recurring test steps can easily be re-used. It’s up to you how fine-grained you want to record your test steps. Calling a step (consisting of one or more actions) is just a matter of a single function call. </li>
<li>Generates C# and XML code by default. </li>
<li>Features fuzzy matching of UI elements. This seems to make the tests more robust when updating the user interface. </li>
</ul>
<p><strong>The Bad:</strong></p>
<ul>
<li>Even very simple tests generate a lot of code. </li>
<li>Test steps are stored in an XML file (called UIMap) which in turn compiles to C# code. The UIMap is big and clunky and there currently is no editor or documentation for it. So if you want to make some changes, things can get complicated unless you want to re-record an entire test step. </li>
<li>Creating very simple assertions (such as “look for the string “foo” on this web page”) is a bit clumsy and requires too many mouse clicks. An IE accelerator would be great! </li>
<li>No support for Safari, Opera or Chrome. On the bright side, Coded UI has an open interface, so anyone could implement it. </li>
<li>While fuzzy matching works great in most cases, It can get in the way in others.</li>
<li>Not quite as intuitive as Selenium at the beginning. </li>
<li>Tests record and run quite a bit slower than with Selenium. </li>
</ul>
<p>&#160;</p>
<h2>Summary</h2>
<p>In essence Selenium looks like a great lightweight tool with a lot of potential, but also with big disadvantages. I wouldn’t even have had a look at Coded UI if only the Selenium IDE was more stable and test steps could be wrapped into groups without custom coding.</p>
<p>But as it is right now, I would only work with Selenium by recording each test separately, exporting it as a C# NUnit test and copying / pasting code into my own test library. This should work around the stability issues, but it is quite tedious.</p>
<p>Coded UI on the other hand is clunky, but stable. Workflow is not nearly as smooth as with Selenium, but still quite good. And it works with C# code instead of JavaScript, which is a big plus for me. Now if only there was a good editor for previously recorded tests built into Visual Studio…</p>
<p>In the end I’ve decided to use Coded UI. It’s not perfect, but it is very good first product iteration. Due to Selenium’s stability issues it looks like the better choice for me at the moment.</p>
<p><strong>Some useful links for getting started:</strong></p>
<ul>
<li><a href="http://seleniumhq.org/docs/">The official Selenium documentation</a> </li>
<li><a href="http://wiki.openqa.org/display/SIDE/Contributed+Extensions+and+Formats" target="_blank">Useful Selenium extensions</a></li>
<li><a title="http://www.oweng.net/Visual-Studio-2010/Coded-UI/Coded-UI-introduction-google-search-results-1.aspx" href="http://www.oweng.net/Visual-Studio-2010/Coded-UI/Coded-UI-introduction-google-search-results-1.aspx">OwenG&#8217;s introduction to Coded UI</a> </li>
<li><a href="http://blogs.msdn.com/gautamg/archive/2009/12/18/why-is-coded-ui-test-generated-code-not-a-straight-line-code.aspx">Some tips on structuring CodedUI Tests by Gautam Goenka</a> </li>
</ul>
<h2>Edit from 12/05/2010: Actually it’s a draw…</h2>
<p><strong> </strong>As I just found out , there is a way to re-use test steps in Selenium IDE without custom coding:</p>
<ul>
<li>Create a separate test case for each sequence of steps that should be made reusable. (such as “create a blog article”)</li>
<li>Create separate test suites for each test that should reuse those test steps. For example you might have a test suite with the tests “Create a blog article” “Edit the blog article” and one with the tests “Create a blog article”, “Delete the blog article”. Note that this is just a poor example since you could also cover both in one single test suites, but as tests become more complex having all reusable test steps in on single test suite becomes impractical.</li>
<li>You have <a href="http://wiki.openqa.org/display/SIDE/Automating+Selenium+IDE+tests" target="_blank">several different options</a> for running all test suites in sequence.</li>
</ul>
<p>This makes Selenium a much more attractive choice. Since I have not written too many tests in Coded UI yet and I prefer the workflow of the Selenium IDE, I am now implementing some of my tests in both frameworks to see which approach leads to more robust and maintainable tests in the long run. </p>
<p>&#160;</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2ftesting%2fselenium-vs-coded-ui-my-perspective%2f"><img border="0" alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2ftesting%2fselenium-vs-coded-ui-my-perspective%2f" /></a>&#160;&#160;&#160; <a href="http://dotnetshoutout.com/User-Interface-Testing-with-Selenium-Vs-Coded-UI-devermindcom" rev="vote-for"><img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdevermind.com%2Ftesting%2Fselenium-vs-coded-ui-my-perspective%2F" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/testing/selenium-vs-coded-ui-my-perspective/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2008 randomly hangs when opening .aspx .ascx or .master files</title>
		<link>http://devermind.com/aspnet/visual-studio-2008-randomly-hangs-when-opening-aspx-ascx-or-master-files/</link>
		<comments>http://devermind.com/aspnet/visual-studio-2008-randomly-hangs-when-opening-aspx-ascx-or-master-files/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 13:12:27 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[visual-studio asp.net]]></category>

		<guid isPermaLink="false">http://devermind.com/aspnet/visual-studio-2008-randomly-hangs-when-opening-aspx-ascx-or-master-files/</guid>
		<description><![CDATA[Visual Studio 2008 has been running quite smoothly on my computer until this week. But then it started randomly hanging when opening an .aspx .ascx .master file. The problem even occurred when opening the file in isolation, instead of opening the file as part of a solution. Deactivating all add-ins did not help. 
Fortunately It [...]]]></description>
			<content:encoded><![CDATA[<p>Visual Studio 2008 has been running quite smoothly on my computer until this week. But then it started randomly hanging when opening an .aspx .ascx .master file. The problem even occurred when opening the file in isolation, instead of opening the file as part of a solution. Deactivating all add-ins did not help. </p>
<p>Fortunately It seems I just found the solution: After uninstalling the &#8220;Microsoft Visual Studio Web authoring Component&#8221;, the problem seems have to have disappeared. I&#8217;m not even sure what this component does, but it seems to be a relict from Visual Studio 2005 and so far I have not noticed any missing features since I uninstalled it.</p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet/visual-studio-2008-randomly-hangs-when-opening-aspx-ascx-or-master-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #4: Client-side form validation made easy &#8211; Part 2</title>
		<link>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/</link>
		<comments>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 13:00:49 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[client-side form validation]]></category>
		<category><![CDATA[client-side validation]]></category>
		<category><![CDATA[dataannotationsmodelbinder]]></category>
		<category><![CDATA[form validation]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery.validate]]></category>
		<category><![CDATA[remote validation]]></category>
		<category><![CDATA[xVal]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=219</guid>
		<description><![CDATA[In my previous article about ASP.NET MVC Client-Side validation, I showed how to set up your project so that you don&#8217;t have to write any custom JavaScript code for any new validation rules. This approach also covered remote client-side  validation  &#8211; these are rules which require server-side resource in order if a particular [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/">previous article</a> about ASP.NET MVC Client-Side validation, I showed how to set up your project so that you don&#8217;t have to write any custom JavaScript code for any new validation rules. This approach also covered remote client-side  validation  &#8211; these are rules which require server-side resource in order if a particular input field is valid or not.</p>
<p>Since I wrote the first part of the article, Steve Sanderson adopted my idea of automatic client-side validation and baked a similar feature right into the latest version of <a href="http://xval.codeplex.com/">xVal</a>. </p>
<p>One important thing is still missing though: What do you do when validation depends on server-side resources but also involves several different form fields? For example, let&#8217;s assume you were implementing a form for your website users to update their contact information. </p>
<p><span id="more-219"></span></p>
<p><strong>Figure 1 &#8211; Example update form</strong><br />
<a href="http://devermind.com/wp-content/uploads/2010/01/Figure1.png"><img src="http://devermind.com/wp-content/uploads/2010/01/Figure1.png" alt="Figure1 - Example update form" title="Figure1 - Example update form" width="804" height="240" class="alignnone size-full wp-image-220" /></a></p>
<p>The form is very similar to the signup form from the last part of this article. However this time  instead of adding new data to the database, the user needs to update his e-mail address. Validation still has to check that the e-mail address entered does not already exist yet. However, this time  it should ignore the current user&#8217;s e-mail address. </p>
<p>For example, if the current user&#8217;s e-mail address is adrian@lobstersoft.com, then we still want to accept this as valid input. But if he enters &#8220;john@doe.com&#8221; and that e-mail address is already taken, we want client-side validation to fail. </p>
<p><a href="http://devermind.com/wp-content/uploads/2010/01/Figure2.png"><img src="http://devermind.com/wp-content/uploads/2010/01/Figure2.png" alt="Figure 2 -  Client-side validation in action" title="Figure 2 -  Client-side validation in action" width="788" height="234" class="alignnone size-full wp-image-221" /></a></p>
<p>And all of this should of course work automatically on both the server and client side simply by providing a server-side validation rule and attaching it the Viewmodel:</p>
<p>Listing 1 &#8211; ViewModel with client/server side enabled entity validation attribute</p>
<pre class="brush: csharp;">
    [EmailUnique]
    public class UserModel
    {
        public int ID{ get; set;}

        [Required(ErrorMessage = &quot;E-mail address is missing.&quot;)]
        [RegularExpression(EmailRegEx, ErrorMessage = &quot;Invalid e-mail address.&quot;)]
        [EmailUnique]
        public string Email { get; set; }

        public class EmailUniqueAttribute : RemoteEntityValidator
        {
            public EmailUniqueAttribute()
                : base(new string[] { &quot;Email&quot;, &quot;ID&quot; }, typeof(User))
            {
                ErrorMessage = &quot;Someone else has already signed up with this e-mail address.&quot;;
            }

            protected override bool EntityValid(object value)
            {
                User entity = (User)value;
	      //make sure there is no user with a different ID but same e-mail address
                return !new FakeUsersRepository().LoadAll().Any(u =&gt; u.ID != entity.ID &amp;&amp; u.Email == entity.Email);
            }
        }

	// Other UserModel properties and validation attributes...
}
</pre>
<h2>Behind the scenes</h2>
<p>Validation of the e-mail input on this form depends on two variables: The user&#8217;s e-mail address and his user ID. </p>
<p>Therefore we need to:</p>
<p>1. Store the user id as a hidden form input field<br />
2. Provide a client-side Javascript function that creates a remote validation rule that submits all relevant form input fields for the particular validation rule to the server.<br />
3. Provide a server-side action method that triggers the validation attribute&#8217;s IsValid method and returns the result to the client-side remote validator. </p>
<p>The approach is quite similar to remote property validation, except that multiple form input fields have to be provided to the server, but there are also a few other other minor differences. For  example the client-side remote validation rules must also be re-validate when one of the other form input elements that validation depends on is changed.  </p>
<p>But the good news is that all of this can be still solved in a generic way so that you can get away just by coding your server-side data annotation validation attributes &#8211; Very similar to the technique shown in the first part of this article. </p>
<h2>Using the RemoteEntityValidator</h2>
<p>For using the code provided with this article in your own project, proceed as follows: </p>
<p>1. Add Xval, jquery.validate, DataAnnotationModelBinder and the code provided in this article&#8217;s demo project to your project as shown in the first part of this article.<br />
2. Next, whenever you need to write a validation attribute that depends on multiple properties of your view model, derive your validation attribute from RemoteEntityValidator as shown in Listing 1. </p>
<p>These are the differences you have to mind in comparison to the RemotePropertyValidator from the first part of the article:</p>
<p>• The RemoteEntityValidator&#8217;s constructor takes one more variable than the RemotePropertyValidator: A string array of all property names in the ViewModel which are relevant for running the validation rule. I guess this could also be done in a more type-safe way by using Linq expressions, but I chose strings for the sake of a simpler syntax, especially when handling many different form fields. </p>
<p>• Note that even though the RemoteEntityValidator depends on several model properties, you must not apply it to all relevant properties in your model. Just apply it to the ViewModel entity and the property that corresponds to the html input element where you want the client-side validation error to appear. However, you do have to apply it both to the ViewModel property AND to the ViewModel class. The property-level attribute is needed for the triggering client side validation when the input element is changed, and the entity-level attribute is needed for server side validation to work. </p>
<p>• Your html form needs to have an ID attribute. It could be done without, but in my project this led to some problems with client-side validation when the form was reloaded via ajax. That&#8217;s why I changed the client-side code for retrieving form input values to something more stable since posting the first part of this article.  </p>
<p><a href='http://devermind.com/wp-content/uploads/2010/01/RemoteValidation.zip'><strong>Download the demo project</strong></a></p>
<h2>Conclusion</h2>
<p>You have learned how to implement client- and server-side validation in a completely generic, model-oriented way. This part of the article completed the technique shown before with validation attributes that depend on several model properties. </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2fwp-admin%2fpost.php%3faction%3dedit%26post%3d219%26message%3d1"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2fwp-admin%2fpost.php%3faction%3dedit%26post%3d219%26message%3d1" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/ASPNET-MVC-Tip-4-Client-side-form-validation-made-easy-Part-2-devermindcom"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdevermind.com%2Faspnet-mvc%2Fasp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2%2F" style="border:0px"/></a></p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #3: Client-side form validation made easy &#8211; Part 1</title>
		<link>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/</link>
		<comments>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 11:00:58 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[client-side form validation]]></category>
		<category><![CDATA[client-side validation]]></category>
		<category><![CDATA[dataannotationsmodelbinder]]></category>
		<category><![CDATA[form validation]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery.validate]]></category>
		<category><![CDATA[remote validation]]></category>
		<category><![CDATA[xVal]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=152</guid>
		<description><![CDATA[Client-side form validation has become a de-facto standard for modern web applications. However, replicating server-side validation rules on the client side can be a tedious and error-prone process. 
In addition, there are some validation rules which cannot be checked completely on the client side, for example because the validation depends on information stored in the [...]]]></description>
			<content:encoded><![CDATA[<p>Client-side form validation has become a de-facto standard for modern web applications. However, replicating server-side validation rules on the client side can be a tedious and error-prone process. </p>
<p>In addition, there are some validation rules which cannot be checked completely on the client side, for example because the validation depends on information stored in the server database. For those rules you need to implement remote client-side form validation. </p>
<p>The xVal framework is great for automatic generation of client-side validation code for some of your server-side validation rules, but it does not support remote client-side validation.</p>
<p>This article shows a fully generic way to implement remote client-side form validation so that</p>
<p>• Validation rules remain solely in your ASP.NET MVC model<br />
• You write each validation rule just once, and only in easily testable C# code.  There is no JavaScript or other client-side counterpart .<br />
• There is no need to branch or otherwise modify xVal or jquery.validate<br />
• All you have to do for each new remote form validation rule is to derive from the base class shown in this article.</p>
<p>I&#8217;ll describe how to implement this in detail. I&#8217;ve also uploaded a demo project showing how this works in action. </p>
<p><span id="more-152"></span></p>
<h2>A brief example</h2>
<p>Let&#8217;s assume you are implementing a website signup form. For the sake of simplicity, lets limit the form to asking for an e-mail address and a password. </p>
<p><strong>Figure 1 &#8211; Example signup form</strong></p>
<p><a href="http://devermind.com/wp-content/uploads/2009/06/emptyform.png"><img src="http://devermind.com/wp-content/uploads/2009/06/emptyform.png" alt="emptyform" title="emptyform" width="585" height="186" class="alignnone size-full wp-image-154" /></a></p>
<p>You want to implement the signup form with both client and server side validation. For the e-mail field, let&#8217;s enforce the following validation rules:</p>
<p>1. Email address is not missing<br />
2. Email address looks valid<br />
3. There is no other user with the same e-mail address in your database. </p>
<p>Rules  1 and 2 can easily be checked on the client side. However, rule 3 can only be done with remote validation: Your client-side validation script needs to connect to your web server and ask if the e-mail address is already taken. </p>
<p>In our example, the only user already in the databse shall be adrian@lobstersoft.com. As soon as someone enters this e-mail address in the form and hits tab, return, or the Create button, an error message should appear before the form has even been posted:</p>
<p><strong>Figure 2 &#8211; Error messages should appear before the form has even been posted</strong></p>
<p><a href="http://devermind.com/wp-content/uploads/2009/06/errorform.png"><img src="http://devermind.com/wp-content/uploads/2009/06/errorform.png" alt="errorform" title="errorform" width="613" height="197" class="alignnone size-full wp-image-155" /></a></p>
<p>Listing 1 shows the entire validation logic necessary for both client and server side validation:</p>
<p><strong>Listing 1 &#8211; Signup form client- and server-side  validation rules</strong></p>
<pre class="brush: csharp;">
using System.ComponentModel.DataAnnotations;

namespace RemoteValidation.Models
{
    public class User
    {
        [Required(ErrorMessage = &quot;E-mail address is missing.&quot;)]
        [RegularExpression(EmailRegEx, ErrorMessage = &quot;Invalid e-mail address.&quot;)]
        [IsNew(ErrorMessage = &quot;Someone has already signed up with this e-mail address.&quot;)]
        public string Email { get; set; }

        [Required(ErrorMessage = &quot;Password is missing.&quot;)]
        public string Password { get; set; }

        public class IsNewAttribute : RemotePropertyValidator
        {
            protected override bool PropertyValid(object value)
            {
                return (string)value != &quot;adrian@lobstersoft.com&quot;;
            }
        }

        private const string EmailRegEx = @&quot;^(([^&lt;&gt;()[\]\\.,;:\s@\&quot;&quot;]+&quot;
                                  + @&quot;(\.[^&lt;&gt;()[\]\\.,;:\s@\&quot;&quot;]+)*)|(\&quot;&quot;.+\&quot;&quot;))@&quot;
                                  + @&quot;((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}&quot;
                                  + @&quot;\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+&quot;
                                  + @&quot;[a-zA-Z]{2,}))$&quot;;
    }
}
</pre>
<p>The SignUp action methods should also be easy to implement since the controller does not need to know anything about our validation rules. </p>
<p><strong>Listing 2 &#8211; Signup form action methods</strong></p>
<pre class="brush: csharp;">
         //
        // GET: /Users/SignUp
        public ActionResult SignUp()
        {
            return View(new User());
        }

        //
        // POST: /Users/SignUp
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SignUp(User model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            //Add User to database and start spamming daemon here

            return RedirectToAction(&quot;SignUpComplete&quot;);
        }
</pre>
<p>Lastly, here&#8217;s how the view above is implemented. </p>
<p><strong>Listing 3 &#8211; Signup form view implementation</strong></p>
<pre class="brush: xhtml;">
&lt;%@ Page Title=&quot;&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Views/Shared/Site.Master&quot; Inherits=&quot;System.Web.Mvc.ViewPage&lt;RemoteValidation.Models.User&gt;&quot; %&gt;

&lt;asp:Content ID=&quot;Content1&quot; ContentPlaceHolderID=&quot;TitleContent&quot; runat=&quot;server&quot;&gt;
    SignUp
&lt;/asp:Content&gt;
&lt;asp:Content ID=&quot;Content2&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;&gt;
    &lt;h2&gt;
        SignUp&lt;/h2&gt;
    &lt;%= Html.ValidationSummary(&quot;SignUp was unsuccessful. Please correct the errors and try again.&quot;) %&gt;
    &lt;% using (Html.BeginForm())
       {%&gt;
    &lt;fieldset&gt;
        &lt;legend&gt;Fields&lt;/legend&gt;
        &lt;p&gt;
            &lt;label for=&quot;Email&quot;&gt;
                Enter your e-mail address:&lt;/label&gt;
            &lt;%= Html.TextBox(&quot;Email&quot;)%&gt;
            &lt;%= Html.ValidationMessage(&quot;Email&quot;, &quot;*&quot;)%&gt;
        &lt;/p&gt;
        &lt;p&gt;
            &lt;label for=&quot;Password&quot;&gt;
                Enter a password:&lt;/label&gt;
            &lt;%= Html.Password(&quot;Password&quot;)%&gt;
            &lt;%= Html.ValidationMessage(&quot;Password&quot;, &quot;*&quot;)%&gt;
        &lt;/p&gt;
        &lt;p&gt;
            Hint: To see that remote validation works, try signing up as &quot;adrian@lobstersoft.com&quot;.
        &lt;/p&gt;
        &lt;p&gt;
            &lt;input type=&quot;submit&quot; value=&quot;Create&quot; /&gt;
        &lt;/p&gt;
    &lt;/fieldset&gt;
    &lt;% } %&gt;

    &lt;%= Html.ClientSideValidation&lt;RemoteValidation.Models.User&gt;()%&gt;
&lt;/asp:Content&gt;
</pre>
<p>Note that the View does not contain any JavaScript or other means to specify client-side validation rules. Everything is done transparently and automatically behind the scenes. </p>
<h2>Prerequisites</h2>
<p>In order for this to work, you need to set up a few things first:</p>
<ol>
<li>
Data Annotation validation attributes for server-side validation. IMO this is the best way to handle server-side validation anyway, even if you are not using client-side validation at all. </p>
<p>Brad Wilson has written a great <a href="http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html">blog article</a> on how to use DataAnnotations in ASP.NET MVC.</p>
<p>Note that there is a bug in DataAnnotationModelBinder which might lead to NullReferenceExceptions when using custom ViewModels. This does not become apparent in our demo project, but if you should encounter this problem, you can find a fix in <a href="http://stackoverflow.com/questions/820468/how-does-dataannotationsmodelbinder-work-with-custom-viewmodels">this StackOverflow posting</a>.
</li>
<li>
Download and reference <a href=" http://bassistance.de/jquery-plugins/jquery-plugin-validation/ ">jquery.validate </a>in your Master Page.
</li>
<li>
Download and reference <a href="http://xval.codeplex.com/">xVal</a>  version 0.8 or later in your project. xVal is a great framework for easy implementation of client-side validation in ASP.NET MVC. It transforms standard server-side validation rules into client-side validation rules recognized by jquery.validate. </p>
<p>Steve Sanderson describes how to set it up and use in <a href="http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/">this blog article</a>.
</li>
</ol>
<p>Once you get this far, you can implement rules 1 and 2 from our example. You could also implement rule 3, although you&#8217;d have to derive it from System.ComponentModel.DataAnnotations.ValidationAttribute, so there would&#8217;t be any client-side validation for that. </p>
<h2>Implementing generic client-side Remote Validation</h2>
<p>While rules 1 and 2 are automagically enforced by xVal on both the client and server side, rule 3 is only checked when the user posts the form. That&#8217;s because xVal does not know what to do with our custom rule. It just looks for standard validation rules like Required, StringLength or RegularExpression and ignores everything else. </p>
<p>Enforcing rule 3 on the client side as well without incurring any additional effort is where the technique I would like to present comes into play.</p>
<p>The first step is not to derive your custom validation rule from ValidationAttribute, but from the RemotePropertyValidator class I implemented. This is already depicted in Listing 1 above. </p>
<p>RemotePropertyValidator is in turn derived from ValidationAttribute, but it also implements xVal&#8217;s ICustomRule interface. This allows it to specify a JavaScript function that should be executed in order to check if the given property is valid on the client side. </p>
<p>RemotePropertyValidator tells xVal to execute the JavaScript function &#8220;RemotePropertyValidation&#8221;. The parameters for this function should be the type of your derived custom validator and the Error message you specified:</p>
<p><strong>Listing 4 &#8211; RemotePropertyValidation class</strong></p>
<pre class="brush: csharp;">
   public abstract class RemotePropertyValidator : ValidationAttribute, ICustomRule
    {
        public CustomRule ToCustomRule()
        {
            return new CustomRule(
                &quot;RemotePropertyValidation&quot;, // JavaScript function name
                new
                    {
                        validator = ToString(),
                        errorMessage = base.ErrorMessage,
                    }, // Params for JavaScript function

                base.ErrorMessage
                );
        }
    }
</pre>
<p>You might be wondering why I am checking for empty  strings / null in Listing 4. That&#8217;s because of differences between how xVal / jquery.validate work on the client side and how the DataAnnotationsModelRunner is implemented on the server side: While it is possible to implicitly implement a Required validator by deriving from ValidationAttribute on the server side, it is not possible to do this with ICustomRule descendents on the client. So I am checking for empty strings / null to avoid inconsistent behaviour. </p>
<p>The ClientSideRegEx property can be set to a regular expression that will be executed on the client before the remote validation is done. You can use it to avoid unnecessary calls to your RemoteValidation controller.</p>
<p>Now, when the user starts typing something in the e-mail field, the browser will execute the JavaScript function &#8220;RemotePropertyValidation&#8221;. Note that this function will receive your derived server-side validator&#8217;s object type and your validator&#8217;s error message  as parameters. </p>
<p>Next, we need to implement a generic RemotePropertyValidation function. In this function we can create a &#8220;remote&#8221; validation rule as supported by jquery.validate and attach it to the Email e-mail input field&#8217;s rules collection:</p>
<p><strong>Listing 5 &#8211; Generic client-side remote validation function</strong></p>
<pre class="brush: javascript;">
function RemotePropertyValidation(value, element, params) {
    var wrappedElement = $(element);
    if (wrappedElement.rules()[&quot;remote&quot;] === undefined) {
        //add optional regEx validator to minimize ajax requests
        if (params.regEx !== null &amp;&amp; wrappedElement.rules()[&quot;xVal_regex&quot;] === undefined) {
            wrappedElement.rules(&quot;add&quot;, {
                xVal_regex: [params.regEx],
                messages: {
                    xVal_regex: params.errorMessage
                }
            });
        }
        var remoteRule =
        //add a new remote validation rule
        wrappedElement.rules(&quot;add&quot;, {
            remote: {
                url: &quot;/RemoteValidation/Property&quot;,
                data: {
                    value: new CreateInputValueAccessor(wrappedElement.attr(&quot;name&quot;)),
                    validator: params.validator
                }
            },
            messages: {
                remote: params.errorMessage
            }
        });

        //validate element again to trigger the new rule(s)
        $(&quot;form&quot;).validate().element(wrappedElement);
    }
    return true;
}

function CreateInputValueAccessor(inputName) {
    return function() {
        return $(&quot;[name=&quot; + inputName + &quot;]&quot;).val();
    };
}
</pre>
<p>The RemotePropertyValidation () function should be referenced in your Master page. Now the first time a user enters something in the Email field , jquery.validate will first validate it using the Required and the Regex rule. If both rules are satisfied, it will check if the e-mail address is already taken with the validation rule that RemotePropertyValidation() inserted on the fly. This will fetch the following URL and parse the JSON reply as validation result.:</p>
<p>http://<Domain>/RemoteValidation/Property?value=<UserInput>&#038;validator=RemoteValidtion.Models.User.IsNew</p>
<p>Now we just need to implement a RemoteValidation that construct an appropriate validator object (note that this is provided in &#8220;validator&#8221; request parameter), let it validate the user input and return the validation result  as JSON: </p>
<p><strong>Listing 6 &#8211; RemoteValidation controller</strong></p>
<pre class="brush: csharp;">
using System;
using System.Reflection;
using System.Web.Mvc;
using RemoteValidation.Models;

namespace RemoteValidation.Controllers
{
    public class RemoteValidationController : Controller
    {
        //
        // GET: /RemoteValidation/Property
        public JsonResult Property()
        {
            Type validatorType = Type.GetType(Request[&quot;validator&quot;], true);
            var validator = (RemotePropertyValidator) Activator.CreateInstance(validatorType);
            return Json(validator.IsValid(Request[&quot;value&quot;]));
        }
    }
}
</pre>
<p>And that&#8217;s it! Now that you have the JavaScript  RemotePropertyValidation function and the remote validation controller in place, all you need to do for new custom validation rules is to derive them from RemotePropertyValidator. This ensures that your validation rules are are automatically enforced on both the server and the client. </p>
<p>For example, all you&#8217;d need to implement for server AND remote client-side validation of password strength is this: </p>
<p><strong>Listing 7 &#8211; Complete implementation of an additional client- and server-side Validator</strong></p>
<pre class="brush: csharp;">
 public class IsSafePasswordAttribute : RemotePropertyValidator
        {

            public IsSafePasswordAttribute()
            {
                //perform some simple password strength check with a regular expression
                //on the client side first
                ClientSideRegEx = &quot;.{8,20}&quot;;
            }

            protected override bool PropertyValid(object value)
            {
                //Insert more elaborate server-side / remote client side password checking
                // logic and return result here...
            }
        }
</pre>
<h2>Caveats</h2>
<p>There are a few things you should keep in mind when using this technique: </p>
<ul>
<li>
You can&#8217;t implicitly implement a Required validator using this technique, so if a property is not optional, you must always decorate it with a Required validator apart from of your own RemotePropertyValidator descendant. It wouldn&#8217;t really make sense to implement a Required validator this way anyway. Please see the Implementation section above if you are interested in the reason for this. </li>
<li>
You can only apply one remote validation rule per form field. This is a limitation of jquery.validate, and it makes sense not to have more than one remote validation rule anyway since you want to minimize the amount of server postbacks as much as possible. If you need to remotely check two different rules on the same property, you can always write a new rule which incorporates both checks, so the only problem is finding an error message that fits both validation rules.
</li>
<li>
This approach only works for Validation Attributes applied to properties, not to entire business entities. I&#8217;ll discuss a similar approach for validating entire business entities in the second part of this article.
</li>
</ul>
<p><a href='http://devermind.com/wp-content/uploads/2009/06/RemoteValidation.zip'>Download the finished demo project </a></p>
<h2>Summary</h2>
<p>Now you know how to implement remote client-side validation without writing any custom JavaScript code.  I discussed how to implement all validation rules, even those that can only be checked on the server, on both the client AND server side in C# code only. I showed how you can do this without any additional effort when implementing new rules. </p>
<p>The only real limitation is that the business rule can check only a single property, not an entire business entity. Stay tuned for the second part of this article, where I&#8217;ll discuss how to circumvent this limitation in a similarly easy way. </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2faspnet-mvc%2fasp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2faspnet-mvc%2fasp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p>
<a rev="vote-for" href="http://dotnetshoutout.com/ASPNET-MVC-Tip-3-How-to-cover-ALL-your-client-side-form-validation-needs-without-writing-any-JavaScript-devermindcom"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdevermind.com%2Faspnet-mvc%2Fasp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1" style="border:0px"/></a></p>
<p><strong>Edit:</strong> The second part of this article has already been posted <a href="http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/feed/</wfw:commentRss>
		<slash:comments>40</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #2: Turn on compile-time View Checking</title>
		<link>http://devermind.com/aspnet/aspnet-mvc-tip-turn-on-compile-time-view-checking/</link>
		<comments>http://devermind.com/aspnet/aspnet-mvc-tip-turn-on-compile-time-view-checking/#comments</comments>
		<pubDate>Sun, 03 May 2009 14:01:32 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[MSBuild]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=139</guid>
		<description><![CDATA[I like the compiler to catch as many errors as possible before I start debugging or release my application. This also applies to code nuggets in ASP.NET MVC views, especially since these are not unit-testable. This article shows how to enable compile-time View checking for ASP.NET MVC projects. ]]></description>
			<content:encoded><![CDATA[<p>I like the compiler to catch as many errors as possible before I start debugging or release my application. This also applies to code nuggets in ASP.NET MVC views, especially since these are not easily unit-testable. But views are not validated at compilation, at least not when using the standard settings for ASP.NET MVC projects.</p>
<p>Tools like Resharper can notify you of syntax errors within your views, but you can still build the project and not get a single error.  Instead, your application will crash when trying to evaluate the buggy view.</p>
<p>Fortunately you can easily make Visual Studio compile your views along with the rest of your code.<span id="more-139"></span> The only downside is that your project will build a bit slower, but if this bothers you during development you can also enable this feature on a per configuration basis.  For example you may want to compile your views in Release mode, but not in your Debug configuration , so you have the extra safety of compile-time view checking before releasing a new version, but you still get lightning-fast compilation times while developing.</p>
<p>Please proceed as follows to turn on compile time view compilation:</p>
<ol>
<li>Open your .csproject or .vbproject file in a text editor of your choice. It’s just a simple xml file, which is why any editor will do fine.</li>
<li>Locate the &lt;PropertyGroup&gt; element that belongs to the configuration you would like to alter.</li>
<li>Within this PropertyGroup, add an additional  element with “true” as its text value.</li>
</ol>
<p>For example, this will turn on view compilation in my project&#8217;s Release configuration:</p>
<pre class="brush: xml;">

&lt;PropertyGroup Condition=&quot; '$(Configuration)|$(Platform)' == 'Release|AnyCPU' &quot;&gt;

&lt;MvcBuildViews&gt;true&lt;/MvcBuildViews&gt;

...
</pre>
<p>That&#8217;s it! The next time one of your views has compile-time errors, these will be reported when building your application.</p>
<p>One last thing: You need to repeat this procedure for all configurations you might create in the future if you want your views to be checked in those configurations as well. Even if you tell Visual Studio to copy settings from an existing configuration where this tag is already set to true, the  MvcBuildViews tag is not copied by Visual Studio.</p>
<p><strong>Edit:</strong> As some readers pointed out, your project&#8217;s compilation time will increase after turning on view compilation. For this reason, I have recently switched it off for the debug configuration of my current project. However, compile-time view compilation is still tremendously useful before releasing a new version. Or perhaps even before submitting a new revision to your source control server. It can catch a lot of different errors this way, especially if you are using the new ASP.NET MVC <a href="http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx">strongly typed Html helpers</a>. </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-tip-turn-on-compile-time-view-checking"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-tip-turn-on-compile-time-view-checking" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://devermind.com/linq/aspnet-mvc-tip-turn-on-compile-time-view-checking"><br />
<img style="border:0px" src="http://dotnetshoutout.com/image.axd?url=http://devermind.com/linq/aspnet-mvc-tip-turn-on-compile-time-view-checking" alt="Shout it" /><br />
</a></div>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet/aspnet-mvc-tip-turn-on-compile-time-view-checking/feed/</wfw:commentRss>
		<slash:comments>52</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #1: Using Custom ViewModels with POST action methods</title>
		<link>http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/</link>
		<comments>http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/#comments</comments>
		<pubDate>Sat, 18 Apr 2009 11:44:27 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[viewmodel]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=102</guid>
		<description><![CDATA[One of the top good practices for ASP.NET MVC is not to use the ViewData Dictionary, but to put your data in a strongly typed ViewModel instead. Many people seem to be using Linq to SQL entities as a ViewModel, because it&#8217;s a very comfortable approach. But what do you do if your view should [...]]]></description>
			<content:encoded><![CDATA[<p>One of the top good practices for ASP.NET MVC is not to use the ViewData Dictionary, but to put your data in a strongly typed ViewModel instead. Many people seem to be using Linq to SQL entities as a ViewModel, because it&#8217;s a very comfortable approach. But what do you do if your view should contain data that is not included in any of your linq entities? <a href="http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx">Scott Gu&#8217;s chapter 1 preview of his upcoming ASP.NET MVC book</a> recommends using a custom-shaped ViewModel for those cases.<span id="more-102"></span></p>
<p>One thing that still puzzled me after reading and trying to follow the chapter was how to create complex custom ViewModels (as opposed to putting all data in the ViewData dictionary or using vanilla Linq to SQL entities). Scott mentions on page 107 of the book  that you &#8220;might have the action method update a ViewModel object with the form-posted data, and then use the ViewModel instance to map or retrieve an actual domain model object&#8221;, but there is no actual example of how this would look in source code.</p>
<p>For example, let&#8217;s assume you have an edit action method with the following view:</p>
<p><a href="http://devermind.com/wp-content/uploads/2009/04/form1.png"><img class="alignnone size-full wp-image-103" title="EditForm" src="http://devermind.com/wp-content/uploads/2009/04/form1.png" alt="EditForm" width="274" height="334" /></a></p>
<p>So your edit form displays data coming from a Linq entity representing a customer (FirstName, LastName, Email, Country, AccountType), but you also need SelectLists to populate the Country and AccountType DropDownLists.</p>
<p><strong>The simple, but untyped approach: the ViewData dictionary</strong></p>
<p>The simplest approach is to use the Customer Linq entity as ViewModel and to put the two SelectLists in the ViewData dictionary. This works fine, but I dislike the fact that there is no type-safety for the two SelectLists. Instead you have to use a type cast from object to SelectList:</p>
<pre class="brush: xml;">
&lt;label for=&quot;CountryCode&quot;&gt;Country&lt;/label&gt;&lt;br /&gt;
&lt;%= Html.DropDownList(&quot;CountryCode&quot;,ViewData[&quot;Countries&quot;] as SelectList)%&gt;

&lt;%= Html.ValidationMessage(&quot;CountryCode&quot;, &quot;*&quot;)%&gt;
</pre>
<p><strong>The fully typed approach: Custom ViewModels</strong></p>
<p>So you want fully typed model data, but the linq entity does not hold all the data you need to render the view. Since you don&#8217;t want to clutter my Customer Linq to SQL entity with two properties that return the two SelectLists, the only alternative to get a fully typed view is to use a custom ViewModel:</p>
<pre class="brush: csharp;">public class CustomersFormViewModel
{
public SelectList AccountTypes { get; set; }
public SelectList Countries { get; set; }
public Customer Customer { get; set; }
}</pre>
<p>Note that the ViewModel is not a mere Linq entity anymore. Instead, it contains the one Customer Linq entity instance, plus the two SelectLists for my DropDownLists.</p>
<p>Now you can implement your view without using any typecasts:</p>
<pre class="brush: html;">

&lt;p&gt;

&lt;label for=&quot;Customer.FirstName&quot;&gt;

FirstName:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;Customer.FirstName&quot;)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.FirstName&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.LastName&quot;&gt;

LastName:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;Customer.LastName&quot;)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.LastName&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.Email&quot;&gt;

Email:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;Customer.Email&quot;)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.Email&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.CountryCode&quot;&gt;

Country&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.DropDownList(&quot;Customer.CountryCode&quot;,Model.Countries)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.CountryCode&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.AccountType&quot;&gt;

AccountType:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.DropDownList(&quot;Customer.AccountType&quot;,Model.AccountTypes)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.AccountType&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;</pre>
<p>I was wondering if the MVC framework can automatically map the form values and reconstruct a CustomersFormViewModel. In other words, can I simply implement a strongly typed POST edit action method and receive a fully populated ViewModel as a parameter like this:</p>
<pre class="brush: csharp;">
//POST: /CustomersController/Edit

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(CustomersFormViewModel model)
{
//validate data, save customer, handle validation errors...
}</pre>
<p>The answer is yes! The MVC framework even maps object hierarchies of any depth as ViewModels.</p>
<p><strong>How not to do it</strong></p>
<p>This is all really easy, but still there were few things that threw me off at the beginning.</p>
<p>The ViewModelBinder only maps properties, not public fields. A ViewModel like this cannot be mapped:</p>
<pre class="brush: csharp;">public class CustomersFormViewModel
{
public electList AccountTypes;
public SelectList Countries;
public Customer Customer;
}</pre>
<p>The names of your POSTed form values must match the object hiearchy you want them to be mapped to. Something like this will not work:</p>
<p style="margin: 0in; font-family: Calibri; font-size: 11pt;">
<pre class="brush: xhtml;">&lt;p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;

&lt;label for=&quot;FirstName&quot;&gt;

FirstName:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;FirstName&quot;,Model,Customer,FirstName)%&gt;

&lt;%= Html.ValidationMessage(&quot;FirstName&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;</pre>
<p>In hindsight both restrictions are perfectly logic and reasonable, but it&#8217;s easy enough to do it wrong nevertheless and also quite difficult to figure out what went wrong if binding does not work. Hopefully this article will help you avoid any problems with using Custom ViewModels with POST action methods.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-using-custom-viewmodels-with-post-action-methods"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-using-custom-viewmodels-with-post-action-methods" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods"><br />
<img style="border:0px" src="http://dotnetshoutout.com/image.axd?url=http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods" alt="Shout it" /><br />
</a></div>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Beginner&#8217;s Guide</title>
		<link>http://devermind.com/aspnet-mvc/aspnet-mvc-beginners-guide/</link>
		<comments>http://devermind.com/aspnet-mvc/aspnet-mvc-beginners-guide/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 12:19:23 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=98</guid>
		<description><![CDATA[I&#8217;ve decided take Microsoft&#8217;s brand new ASP.NET MVC framework for a small test drive by building a small proof of concept application with it. The frame work sure looks promising, even despite it&#8217;s early stage of development and relatively small features as compared to ASP.NET web forms. 
It seems there are no good books available [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve decided take Microsoft&#8217;s brand new ASP.NET MVC framework for a small test drive by building a small proof of concept application with it. The frame work sure looks promising, even despite it&#8217;s early stage of development and relatively small features as compared to ASP.NET web forms. </p>
<p>It seems there are no good books available on the subject yet. The few that are already in stock at Amazon are based on the community preview, and it seems that there have been quite a few changes in the the framework since then. </p>
<p>Fortunately, ScottGu hat just released a free sample chapter of his upcoming &#8220;Professional ASP.NET&#8221; (Wrox) book. It contains a 200-page walkthrough guide on how to build a simple ASP.NET MVC application. </p>
<p>The chapter is available for download <a href="http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx">here</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet-mvc/aspnet-mvc-beginners-guide/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Interview on Shareware Radio</title>
		<link>http://devermind.com/business/interview-on-shareware-radio/</link>
		<comments>http://devermind.com/business/interview-on-shareware-radio/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 13:03:36 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[shareware]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=91</guid>
		<description><![CDATA[Mike Dulin has just published an interview we recorded at last year&#8217;s European Shareware Conference. We talked a bit about shareware games vs. casual games, how I got into the games business and the current market climate in both areas. The Interview is available here.
]]></description>
			<content:encoded><![CDATA[<p>Mike Dulin has just published an interview we recorded at last year&#8217;s European Shareware Conference. We talked a bit about shareware games vs. casual games, how I got into the games business and the current market climate in both areas. The Interview is available <a href="http://www.sharewareradio.com/week090226.htm">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/business/interview-on-shareware-radio/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Updated: Generic base class for LINQ2SQL data layers</title>
		<link>http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers/</link>
		<comments>http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 14:23:32 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[DAL]]></category>
		<category><![CDATA[multi-tier]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=79</guid>
		<description><![CDATA[Hi,
It&#8217;s been a while since I posted the first version of my generic base class for LINQ2SQL data layers. The idea behind this class was to provide a quick and simple way to implement a repository with LINQ2SQL and therefore also a solid foundation for implementing your n-tier architecture data layer. If you missed the [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>It&#8217;s been a while since I posted the first version of my generic base class for LINQ2SQL data layers. The idea behind this class was to provide a quick and simple way to implement a repository with LINQ2SQL and therefore also a solid foundation for implementing your n-tier architecture data layer. If you missed the article, you can read more about the base class <a href="http://devermind.com/linq/a-linq-disconnected-mode-abstract-base-class">here</a>.</p>
<p>The version I previously posted has worked fine for me, but it was still lacking a way to retrieve the ID and version attributes of saved entities. Due to a typo, it also did not work with entities that have more than one unique identity column. Thanks to Mike and Fabrizio for pointing out these limitations!</p>
<p>Version 0.2 available here fixes both of these issues:</p>
<p><a href="http://devermind.com/wp-content/uploads/2009/02/repositorybase_demo_02.zip">Download RepositoryBase Demo Website</a></p>
<p><a href="http://devermind.com/wp-content/uploads/2009/02/repositorybase_source_02.zip">Download RepositoryBase Source Code Only</a></p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
	</channel>
</rss>
