<?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>Charles Vallance</title>
	<atom:link href="http://www.pagedesigners.co.nz/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.pagedesigners.co.nz</link>
	<description>Web development ramblings from a Kiwi in Canada</description>
	<lastBuildDate>Wed, 20 Jul 2011 22:35:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Modal Forms with ASP.NET MVC 3 and jQuery – Part 1.1: The other forms</title>
		<link>http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-%e2%80%93-part-1-1-the-other-forms/</link>
		<comments>http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-%e2%80%93-part-1-1-the-other-forms/#comments</comments>
		<pubDate>Wed, 20 Jul 2011 22:34:19 +0000</pubDate>
		<dc:creator>charles</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.pagedesigners.co.nz/?p=71</guid>
		<description><![CDATA[Posts in the Modal Forms with ASP.NET MVC 3 and jQuery series: Part 1: Just get it to work Part 1.1: The other forms Part 2: Clean up and conventions (coming soon) Part 3: Summary and overview (coming soon(ish)) After &#8230; <a href="http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-%e2%80%93-part-1-1-the-other-forms/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Posts in the Modal Forms with ASP.NET MVC 3 and jQuery series:</p>
<ul>
<li><a href="http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-part-1-just-get-it-to-work/">Part 1: Just get it to work</a></li>
<li>Part 1.1: The other forms</li>
<li>Part 2: Clean up and conventions (coming soon)</li>
<li>Part 3: Summary and overview (coming soon(ish))</li>
</ul>
<p>After I finished my last post, <a href="http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-part-1-just-get-it-to-work/">Modal Forms with ASP.NET MVC 3 and jQuery – Part 1: Just get it to work</a>, I updated all the other forms so they were also modal popups.</p>
<p><a href="https://github.com/cvallance/ModalForms/commit/6f438d9bbddc2c97bdb87040d747375434a42ee2">View GitHub Commit</a></p>
<p>Now that all the forms have been turned into modal forms, you should notice that there is a lot of repeated code.</p>
<p>Especially note the repetition in the javascript (<a href="https://github.com/cvallance/ModalForms/blob/6f438d9bbddc2c97bdb87040d747375434a42ee2/ModalForms/Scripts/ModalForms.Init.js">here</a> and <a href="https://github.com/cvallance/ModalForms/blob/6f438d9bbddc2c97bdb87040d747375434a42ee2/ModalForms/Scripts/Pages/Account.Details.js">here</a>), this is where most of the clean up will occur.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-%e2%80%93-part-1-1-the-other-forms/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Modal Forms with ASP.NET MVC 3 and jQuery &#8211; Part 1: Just get it to work</title>
		<link>http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-part-1-just-get-it-to-work/</link>
		<comments>http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-part-1-just-get-it-to-work/#comments</comments>
		<pubDate>Fri, 01 Jul 2011 21:24:14 +0000</pubDate>
		<dc:creator>charles</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQueryUI]]></category>

		<guid isPermaLink="false">http://www.pagedesigners.co.nz/?p=29</guid>
		<description><![CDATA[Posts in the Modal Forms with ASP.NET MVC 3 and jQuery series: Part 1: Just get it to work Part 1.1: The other forms Part 2: Clean up and conventions (coming soon) Part 3: Summary and overview (coming soon(ish)) As &#8230; <a href="http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-part-1-just-get-it-to-work/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Posts in the Modal Forms with ASP.NET MVC 3 and jQuery series:</p>
<ul>
<li>Part 1: Just get it to work</li>
<li><a href="http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-%E2%80%93-part-1-1-the-other-forms/">Part 1.1: The other forms</a></li>
<li>Part 2: Clean up and conventions (coming soon)</li>
<li>Part 3: Summary and overview (coming soon(ish))</li>
</ul>
<p>As a ASP.NET MVC developer I find that all my forms tend to follow a very similar pattern. Put simply it starts with a GET, validation occurs on the client, POST with model binding, additional validation on the server and finally I either re-display the form OR redirect to another action with a success message.</p>
<p>To add another twist, I&#8217;ve been using jQuery UI modal dialogs to display a number of the smaller forms, e.g. log on, registration, change password, etc.</p>
<p>With all of this going on, I&#8217;ve created a nice and easy way to do this using conventions so any modal forms I create require very little effort to setup. And because I&#8217;m such a nice guy, I&#8217;m going to share it with all of you!</p>
<p>For the purpose of this blog series I started with new ASP.NET MVC 3 Web Application because it conveniently already has log in, register and change password forms that can easily be turned into modal forms.</p>
<p>I&#8217;ll be using GitHub through the whole series, so you can follow along and download the code to run on your local machine. I&#8217;ll also be linking to my specific commits as an easy way to show you what&#8217;s going on.</p>
<p>This first post will simply get the modal forms to work. I&#8217;m not going to lie, it gets ugly&#8230; but just know that the follow-up blog posts will clean it all up, so just hang in there.</p>
<p>First things first</p>
<ul>
<li>Move all the javascript to the bottom of the page, it&#8217;s just how I roll (<a href="http://developer.yahoo.com/blogs/ydn/posts/2007/07/high_performanc_5/" target="_blank">for good reason</a>)</li>
<li>Move the jquery.validate.min.js &#038; jquery.validate.unobtrusive.min.js references to the _Layout.cshtml page because they&#8217;ll be needed on most pages.</li>
</ul>
<p><a href="https://github.com/cvallance/ModalForms/commit/e7d2b97bad9ead43884f1eacaafa3528f1dbd8ec" target="_blank">View GitHub Commit</a></p>
<p>Now lets get a modal form popping up. We&#8217;ll start with the log on form.</p>
<p><strong>To do:</strong></p>
<ul>
<li>Reference the jQueryUI JS &#038; CSS</li>
<li>Give the log on link an id so we can reference it in our javascript</li>
<li>Make the log on action return a partial view and clean out any unwanted html from the view</li>
<li>Create a new javascript file to do our bidding</li>
</ul>
<p><a href="https://github.com/cvallance/ModalForms/commit/de634a30a7722f8db5835e5b7ca755eecd79558f" target="_blank">View GitHub Commit</a></p>
<p>Result showing the new modal form:</p>
<p><a href="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-Modal.gif"><img src="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-Modal.gif" alt="" title="LogOn-Modal" width="632" height="536" class="alignnone size-full wp-image-32" /></a></p>
<p>Looking at the GitHub commit, pay particular attention to the new ModalForms.Init.js file, the following things are happening:</p>
<ul>
<li>A new click handler is attached to the log on link</li>
<li>A div, named &#8216;dialogDiv&#8217;, is created and attached to the body of the page</li>
<li>We use the url from the log on link to make a ajax request and populate the dialogDiv through a jQuery .load() call</li>
<li>When the dialogDiv is populated we turn it into a jQueryUI modal dialog</li>
<li>Remove the dialogDiv from the dom when the modal is closed</li>
</ul>
<p>This is all good and we&#8217;re getting somewhere, but the functionally is <a href="http://www.urbandictionary.com/define.php?term=up%20the%20boohai" target="_blank">up the boohai</a>, so lets get things working a bit better.</p>
<p>So whats wrong? Well, to start with the form has lost it&#8217;s client side validation. Luckily because we&#8217;re using the jQuery validation &#038; unobtrusive validation, fixing the client side validation is simple.</p>
<p>By default the unobtrusive validation library parses the page once it loads looking for data- attributes and creates jQuery validation rules for them, but because our modal form is loaded after the original page is loaded, it wasn&#8217;t parsed. The log on form still has all the required data- attributes needed for unobtrusive validation, so all we need to do is get the unobtrusive validation module to parse this new form.</p>
<p><a href="https://github.com/cvallance/ModalForms/commit/264913beded0d232116b052d7c1411390dc92f64" target="_blank">View GitHub Commit</a></p>
<p>Told you it was simple.</p>
<p>Result showing client validation working agian:</p>
<p><a href="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-ClientValidation.gif"><img src="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-ClientValidation.gif" alt="" title="LogOn-ClientValidation" width="630" height="539" class="alignnone size-full wp-image-41" /></a></p>
<p>It&#8217;s probably at this point that I should mention that I&#8217;m not going to mess around with the looks of anything too much, just pretend that things look pretty.</p>
<p>The other major thing that is wrong at this point, is that the modal form is still doing a traditional POST to the server. We want to change this so that it&#8217;s all done through AJAX.</p>
<p><strong>To do:</strong></p>
<ul>
<li>Create a new BaseController that contains a couple of shorthand JsonResults for success and failure</li>
<li>Alter the LogOn POST action to return the new JsonResults</li>
<li>Remove the form&#8217;s default submit button</li>
<li>Create a jQueryUI dialog button that submits the form through an AJAX call</li>
<li>Create a cancel button.</li>
<li>NOTE: I also visited /Account/Register to setup an account to test logging on (TenSpeed:password)</li>
</ul>
<p><a href="https://github.com/cvallance/ModalForms/commit/679261e86af1994c5d45632797ba026ff15952df" target="_blank">View GitHub Commit</a></p>
<p>Result showing POSTs with both invalid and valid credentials:</p>
<p><a href="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-AjaxFormPost.gif"><img src="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-AjaxFormPost.gif" alt="" title="LogOn-AjaxFormPost" width="569" height="413" class="alignnone size-full wp-image-42" /></a></p>
<p>And after the successful log on:</p>
<p><a href="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-LoggedOn.gif"><img src="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-LoggedOn.gif" alt="" title="LogOn-LoggedOn" width="630" height="287" class="alignnone size-full wp-image-43" /></a></p>
<p>Sweet! Now we&#8217;re getting somewhere!</p>
<p>What&#8217;s missing? Well, when there are errors on the server, we need to send them back to the client and then display them.</p>
<p>We&#8217;ll do this in two parts because it&#8217;s a little more complicated than what we&#8217;ve done before. First up, we&#8217;ll get the server side code to send us some errors back, that part is easy.</p>
<p><strong>To do:</strong></p>
<ul>
<li>Create a new ErrorDictionary class to hold the errors that get sent to the client</li>
<li>Add an extension method for ModelStateDictionary to throw all the ModelState errors into an ErrorDictionary</li>
<li>Lastly we need to send the ErrorDictionary back to the client</li>
</ul>
<p><a href="https://github.com/cvallance/ModalForms/commit/7629d70e9d2843e8db2332d2885f2013afb184e4" target="_blank">View GitHub Commit</a></p>
<p>Result showing errors in the response:</p>
<p><a href="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-AjaxErrors.gif"><img src="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-AjaxErrors.gif" alt="" title="LogOn-AjaxErrors" width="599" height="95" class="alignnone size-full wp-image-46" /></a></p>
<p>Nothing too major there, it&#8217;s pretty straight forward. Displaying them on the other hand is easier said than done.</p>
<p>I like my validation errors in a validation summary div, so that&#8217;s how I&#8217;m going to go about this&#8230; again, it&#8217;s just how I roll. So we have to make something that will play nicely with the existing client side validation and something that we can manipulate when we get our errors from the server.</p>
<p><strong>To do:</strong></p>
<ul>
<li>Remove the validation messages from beside the inputs on the log on form</li>
<li>Create validation summary container on the client that the unobtrusive validation will use and that we can manipulate ourselves</li>
<li>Display the errors from the server </li>
</ul>
<p><a href="https://github.com/cvallance/ModalForms/commit/ed1911d0a719fe440132acde3cd58c33dff96498" target="_blank">View GitHub Commit</a></p>
<p>NOTE: I really really really wanted to put the validationSummary stuff inside the ModalForms.Init.js file to make it even more monstrous but I just couldn&#8217;t bring myself to do it ;-)</p>
<p>Result with standard client side validation:</p>
<p><a href="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-ValidationSummary.gif"><img src="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-ValidationSummary.gif" alt="" title="LogOn-ValidationSummary" width="613" height="566" class="alignnone size-full wp-image-47" /></a></p>
<p>And displaying errors from the server:</p>
<p><a href="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-AjaxClientValidation.gif"><img src="http://www.pagedesigners.co.nz/wp-content/uploads/2011/06/LogOn-AjaxClientValidation.gif" alt="" title="LogOn-AjaxClientValidation" width="613" height="538" class="alignnone size-full wp-image-48" /></a></p>
<p>The big update here was the addition of the ModalForms.ValidationSummary.js file, so lets have a look at that in a bit more depth by going through the 5 basic functions in the validationSummary class.</p>
<ul>
<li><strong>setUp</strong> &#8211; this, surprisingly, sets up the validationSummary by either finding an existing one or creating a new one. It takes a jQuery object as a parameter, this object is where the validationSummary should be found or appended to&#8230; in most cases it will be the form.</li>
<li><strong>createNew</strong> &#8211; this will generate the html for a new validationSummary. You should note that the html it generates has a &#8216;data-valmsg-summary&#8217; attribute set to true &#8211; this will enable the client side validation to use it.</li>
<li><strong>addErrors</strong> &#8211; this takes a bunch of errors and puts them into the validationSummary.</li>
<li><strong>addError</strong> &#8211; this adds a single error to the validationSummary.</li>
<li><strong>clearErrors</strong> &#8211; this clears all the errors from the validationSummary and resets everything back to a valid state.</li>
</ul>
<p>And there we have it, a fully working modal log on form.</p>
<p>Now I know that ModalForms.Init.js file aint got no alibi, but we&#8217;re going to take care of that in Part 2 &#8211; Clean up and conventions.</p>
<p>Thanks and stay tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pagedesigners.co.nz/2011/07/modal-forms-with-asp-net-mvc-3-and-jquery-part-1-just-get-it-to-work/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC 3 Email Validation with Unobtrusive jQuery Validation</title>
		<link>http://www.pagedesigners.co.nz/2011/02/asp-net-mvc-3-email-validation-with-unobtrusive-jquery-validation/</link>
		<comments>http://www.pagedesigners.co.nz/2011/02/asp-net-mvc-3-email-validation-with-unobtrusive-jquery-validation/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 01:05:01 +0000</pubDate>
		<dc:creator>charles</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net-mvc jquery jquery-validation]]></category>

		<guid isPermaLink="false">http://50.16.228.129/?p=3</guid>
		<description><![CDATA[I&#8217;ve been searching the web for an example to implement email validation in ASP.NET MVC 3 using unobtrusive jQuery validation, but all I found were all overly convoluted and complex. Maybe my google fu just isn&#8217;t up to scratch? Anyway, &#8230; <a href="http://www.pagedesigners.co.nz/2011/02/asp-net-mvc-3-email-validation-with-unobtrusive-jquery-validation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been searching the web for an example to implement email validation in ASP.NET MVC 3 using unobtrusive jQuery validation, but all I found were all overly convoluted and complex. Maybe my google fu just isn&#8217;t up to scratch?</p>
<p>Anyway, here&#8217;s the code I&#8217;m using that is working a treat.</p>
<pre class="brush: c-sharp">namespace PageDesigners.Library.ValidationAttributes
{
    public class EmailAttribute : RegularExpressionAttribute, IClientValidatable
    {
        public EmailAttribute()
            : base(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                   @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                   @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")
        {
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var errorMessage = FormatErrorMessage(metadata.GetDisplayName());

            yield return new EmailValidationRule(errorMessage);
        }
    }

    public class EmailValidationRule : ModelClientValidationRule
    {
        public EmailValidationRule(string errorMessage)
        {
            ErrorMessage = errorMessage;
            ValidationType = "email";
        }
    }
}</pre>
<p>Then simply use it like so</p>
<pre class="brush: c-sharp">public class SignUpForm
{
    //Blah

    [DisplayName("Your email")]
    [Required(ErrorMessage = "{0} is required.")]
    [Email(ErrorMessage = "{0} appears to be invalid.")]
    public string EmailAddress { get; set; }

    //Blah
}</pre>
<p>Enjoy.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pagedesigners.co.nz/2011/02/asp-net-mvc-3-email-validation-with-unobtrusive-jquery-validation/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Keeping ModelState Errors after HtmlHelper.RenderAction()</title>
		<link>http://www.pagedesigners.co.nz/2010/12/keeping-modelstate-errors-after-htmlhelper-renderaction/</link>
		<comments>http://www.pagedesigners.co.nz/2010/12/keeping-modelstate-errors-after-htmlhelper-renderaction/#comments</comments>
		<pubDate>Sun, 19 Dec 2010 02:42:06 +0000</pubDate>
		<dc:creator>charles</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net-mvc]]></category>

		<guid isPermaLink="false">http://50.16.228.129/?p=5</guid>
		<description><![CDATA[I have recently started rendering some forms in my application into their own partial actions. There are a few reasons I find the decoupling a nice clean solution. The main two reasons are: rendering a form on multiple views getting &#8230; <a href="http://www.pagedesigners.co.nz/2010/12/keeping-modelstate-errors-after-htmlhelper-renderaction/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have recently started rendering some forms in my application into their own partial actions.</p>
<p>There are a few reasons I find the decoupling a nice clean solution. The main two reasons are:</p>
<ul>
<li>rendering a form on  multiple views</li>
<li>getting individual forms using ajax for modal windows</li>
</ul>
<p>Let&#8217;s see how it works. Take a simple register page like the following (based on the default ASP.NET MVC project).</p>
<p><strong>Register.aspx</strong></p>
<pre class="brush: html">&lt;%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage&lt;MvcApplication1.Models.RegisterViewModel&gt;" %&gt;

&lt;asp:Content ID="registerContent" ContentPlaceHolderID="MainContent" runat="server"&gt;

    &lt;h2&gt;Create a New Account&lt;/h2&gt;

    &lt;p&gt;
        Use the form below to create a new account.
    &lt;/p&gt;

    &lt;% Html.RenderAction("RegisterForm"); %&gt;
&lt;/asp:Content&gt;</pre>
<p><strong>RegisterForm.ascx</strong></p>
<pre class="brush: html">&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;MvcApplication1.Models.RegisterFormModel&gt;" %&gt;

&lt;% using (Html.BeginForm()) { %&gt;
    &lt;%: Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.") %&gt;
    &lt;div&gt;
        &lt;fieldset&gt;
            &lt;legend&gt;Account Information&lt;/legend&gt;

            &lt;div class="editor-label"&gt;
                &lt;%: Html.LabelFor(m =&gt; m.UserName) %&gt;
            &lt;/div&gt;
            &lt;div class="editor-field"&gt;
                &lt;%: Html.TextBoxFor(m =&gt; m.UserName) %&gt;
                &lt;%: Html.ValidationMessageFor(m =&gt; m.UserName) %&gt;
            &lt;/div&gt;

            &lt;!-- Blah blah --&gt;

            &lt;div class="editor-label"&gt;
                &lt;%: Html.LabelFor(m =&gt; m.ConfirmPassword) %&gt;
            &lt;/div&gt;
            &lt;div class="editor-field"&gt;
                &lt;%: Html.PasswordFor(m =&gt; m.ConfirmPassword) %&gt;
                &lt;%: Html.ValidationMessageFor(m =&gt; m.ConfirmPassword) %&gt;
            &lt;/div&gt;

            &lt;p&gt;
                &lt;input type="submit" value="Register" /&gt;
            &lt;/p&gt;
        &lt;/fieldset&gt;
    &lt;/div&gt;
&lt;% } %</pre>
<p><strong>AccountController.cs</strong></p>
<pre class="brush: c-sharp">public ActionResult Register()
{
    var viewModel = AccountService.GetRegisterViewModel(MembershipService);
    return View(viewModel);
}

[HttpPost]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        //registration code
    }

    // If we got this far, something failed, redisplay form
    var viewModel = AccountService.GetRegisterViewModel(MembershipService);
    return View(viewModel);
}

public PartialViewResult RegisterForm()
{
    var formModel = AccountService.GetRegisterFormModel();
    return PartialView(formModel);
}</pre>
<p>Got my drift? Good.</p>
<p>But this approach has a problem&#8230; when you call .RenderAction a new controller is spun up, so you loose all the previous controller and view context that was setup &#8211; this is especially important for forms because you lose all the modelstate errors.</p>
<p>Losing modelstate errors is no good at all because the partial view can&#8217;t render any of the errors.</p>
<p><strong>Fix</strong></p>
<p>Conveniently, the ActionExecutingContext contains a property &#8216;ParentActionViewContext&#8217; where we can access the previous modelstate we need.</p>
<p>So all we need to do is create a custom action attribute that populates the partial actions modelstate like so:</p>
<p><strong>KeepParentModelErrors.cs</strong></p>
<pre class="brush: c-sharp">public class KeepParentModelErrors : FilterAttribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ParentActionViewContext == null)
            return;

        var parentContext = filterContext.ParentActionViewContext;

        var modelState = filterContext.Controller.ViewData.ModelState;
        foreach (var modelStateItem in parentContext.ViewData.ModelState)
        {
            if (modelState.ContainsKey(modelStateItem.Key))
            {
                foreach (var error in modelStateItem.Value.Errors)
                {
                    if (!modelState[modelStateItem.Key].Errors.Contains(error))
                        modelState[modelStateItem.Key].Errors.Add(error);
                }
            }
            else
            {
                filterContext.Controller.ViewData.ModelState.Add(modelStateItem);
            }
        }
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //Nothing to do here
    }
}</pre>
<p>Thoughts?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pagedesigners.co.nz/2010/12/keeping-modelstate-errors-after-htmlhelper-renderaction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC, DateTime Binding, and Culture Unaware URLs</title>
		<link>http://www.pagedesigners.co.nz/2009/12/asp-net-mvc-datetime-binding-and-culture-unaware-urls/</link>
		<comments>http://www.pagedesigners.co.nz/2009/12/asp-net-mvc-datetime-binding-and-culture-unaware-urls/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 03:44:00 +0000</pubDate>
		<dc:creator>charles</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net-mvc]]></category>

		<guid isPermaLink="false">http://50.16.228.129/?p=9</guid>
		<description><![CDATA[I came across some interesting behaviour with the ASP.NET MVC 2 Beta yesterday. When I was binding to a DateTime value it would work fine with a POST request but when I switched that to a GET request, everything bombed. &#8230; <a href="http://www.pagedesigners.co.nz/2009/12/asp-net-mvc-datetime-binding-and-culture-unaware-urls/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I came across some interesting behaviour with the ASP.NET MVC 2 Beta yesterday. When I was binding to a DateTime value it would work fine with a POST request but when I switched that to a GET request, everything bombed. Weird.</p>
<p>After a bit more investigation I found it had to do with <a href="http://en.wikipedia.org/wiki/Culture_of_New_Zealand">my culture</a>&#8230; well, rather it had to do with the  GET request binding my date (formatted as &#8216;dd/mm/yyyy&#8217;) using the backwards American date format of &#8216;mm/dd/yyyy&#8217; (flame on).</p>
<p>It was late at night at the time, so I quickly whipped up a very basic ASP.NET MVC application to reproduce the interesting behaviour I was experiencing and fired it off to <a href="http://haacked.com/">Phil Haack</a> &#8211; which in hindsight wasn&#8217;t probably the best route to take, should&#8217;ve followed some sort of procedure and posted it to codeplex project&#8217;s issue tracker instead of bothering Phil.</p>
<p>Anyway&#8230; after a good nights sleep, a good day at work under my belt and no reply from Phil (obviously a busy man and <a href="http://haacked.com/archive/2009/12/14/back-in-business-again.aspx">bigger things to worry about</a>), I decided to have a gander at the issue myself.</p>
<p><!-- more -->After a short time of debuging into the ASP.NET MVC 2 Beta source code, I managed to find the culprit. Surprisingly the issue resided in the QueryStringValueProvider class &#8211; I know, who would&#8217;ve guessed?!</p>
<p>What I found is the following in all its undisguised glory:</p>
<pre class="brush: c-sharp">// QueryString should use the invariant culture since it's part of the URL, and the URL should be
// interpreted in a uniform fashion regardless of the origin of a particular request.
protected override CultureInfo GetCulture(ControllerContext controllerContext) {
    return CultureInfo.InvariantCulture;
}</pre>
<p>My first thought was &#8216;<em>hang on, so this weird behaviour is actually intentional? WTF were they thinking?!?</em>&#8217;. Then, naturally, images of a CultureAwareQueryStringValueProvider swirlled around my head &#8211; easy &#8216;fix&#8217; I thought. But as my testosterone levels started to drop back to normal, I realised that someone smarter than me has obviously made a very conscience decision to make it culture unaware&#8230;</p>
<p>So why is it culture unaware?</p>
<p>Well, if you think about it, a URL is a pointer to a specific resource. So if the url is culture aware, that same URL could point to different resources.</p>
<p>E.g. say there was a URL like:</p>
<p>&#8216;http://www.temp.com/events?from=01/01/2010&amp;to=01/03/2010&amp;page=3&#8217;</p>
<p>If it was culture aware, my culture would expect it to show the 3rd page of events between 1st Jan 2010 &amp; 1st March 2010 BUT someone else&#8217;s inferior culture (flame stoke) might expect it to show the 3rd page of events between 1st Jan 2010 &amp; 3rd Jan 2010.</p>
<p>Making sense now? Good.</p>
<p>So what are my options to fix this? Well, as I see it, there are 3 obvious solutions.</p>
<p>Option 1: Use a POST request instead of a GET request. This really isn&#8217;t an option, in my situation I really need it to be a GET request.</p>
<p>Option 2: Create a custom binding to make the querystring culture aware. This really isn&#8217;t an option because as I outlined above, URLs shouldn&#8217;t be culture aware.</p>
<p>Option 3: Change the date format in the querystring. I.e. use the &#8216;yyyy/mm/dd&#8217; format so that all cultures will understand and interpret the URL the same<sup>1</sup>. This is really the only option for me and I&#8217;m relatively happy with it&#8230; from a technical perspective it&#8217;s super but from a usability perspective (e.g. users having to enter dates in that format), it may not be the best.</p>
<p>Any other ideas dear reader?</p>
<p>EDIT: Got a reply from Phil and he basically backed up my understanding of the situation and gave his take on some solutions similar to those outlined above. Cheers Phil! :-)</p>
<p><sup>1</sup>If someone tells me that some culture recognises the date format &#8216;yyyy/dd/mm&#8217; I&#8217;ll probably cry. Seriously.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pagedesigners.co.nz/2009/12/asp-net-mvc-datetime-binding-and-culture-unaware-urls/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC 2 &#8211; Buddy Classes for your models</title>
		<link>http://www.pagedesigners.co.nz/2009/08/asp-net-mvc-2-buddy-classes-for-your-models/</link>
		<comments>http://www.pagedesigners.co.nz/2009/08/asp-net-mvc-2-buddy-classes-for-your-models/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 23:47:34 +0000</pubDate>
		<dc:creator>charles</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net-mvc]]></category>

		<guid isPermaLink="false">http://50.16.228.129/?p=12</guid>
		<description><![CDATA[With the new release of ASP.NET MVC 2 CTP 1 there are a lot of cool new features that are driven by html attributes on your models. Read both The Gu’s and Phil Haack’s blog posts about the release to &#8230; <a href="http://www.pagedesigners.co.nz/2009/08/asp-net-mvc-2-buddy-classes-for-your-models/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>With the new release of ASP.NET MVC 2 CTP 1 there are a lot of cool new features that are driven by html attributes on your models. Read both <a href="http://weblogs.asp.net/scottgu/archive/2009/07/31/asp-net-mvc-v2-preview-1-released.aspx">The Gu’s</a> and <a href="http://haacked.com/archive/2009/07/30/asp.net-mvc-released.aspx">Phil Haack’s</a> blog posts about the release to get the full low down.</p>
<p>I’m guessing that (like myself) a lot of people out there are using ORM’s to generate their models. Yeah? Thought so. Anyway, looking at that previous sentence, the key word is *generate*. You see, if you put property attributes in these generated files, they’re just going to be wiped each time you make a db schema change – far from ideal! ;-)</p>
<p>So where do you put these attributes?</p>
<p>Nope, you can’t put them in a partial class because C# and VB.NET don’t allow you to add attributes to properties defined in another partial class.</p>
<p>Enter the <strong>Buddy Class</strong>!</p>
<p>The Gu touched on buddy classes in his aforelinked<sup>1</sup> post, but didn’t go into them in any detail – so I’m going to<em> try</em> and fill that void with this post.</p>
<p><!-- more -->Say we have a &#8216;Customer&#8217; table (similar to The Gu&#8217;s example) in our database and our orm generates a class like so:</p>
<pre class="brush: c-sharp">public partial class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
    public string Country { get; set; }
}</pre>
<p>Before we go any further (if you haven’t already) you should add a reference to System.ComponentModel.DataAnnotations.dll to your project – you’re gonna need it.</p>
<p>Next we create a partial class for the generated class and also create it’s buddy class.</p>
<p>The best way to explain this is with code, so here you go:</p>
<pre class="brush: c-sharp">[MetadataType(typeof(Customer_Metadata))]
public partial class Customer
{
    //Custom model stuff here
}

public class Customer_Metadata
{
    [DisplayName("First name")]
    [Required(ErrorMessage = "First name is required")]
    public string FirstName { get; set; }

    [DisplayName("Last name")]
    [Required(ErrorMessage = "Last name is required")]
    public string LastName { get; set; }

    [Range(1, 120, ErrorMessage = "Invalid Age")]
    public int Age { get; set; }

    [Required(ErrorMessage = "Email is required")]
    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Country is required")]
    [UIHint("CountryDropDown")]
    public string Country { get; set; }
}</pre>
<p>Savvy? Good, because that&#8217;s really all there is to it! ;-)</p>
<p><sup>1</sup>aforelinked &#8211; new word? © Charles Vallance 2009</p>
<p><strong>EDIT: Making the buddy class a private inner class</strong></p>
<p>As outlined below by Tyrone and Steve, it&#8217;s probably best practice to have the buddy class as a private inner class.</p>
<p>E.g.</p>
<pre class="brush: c-sharp">[MetadataType(typeof(Customer.Metadata))]
public partial class Customer
{
    //Custom model stuff here

    private sealed class Metadata
    {
        [DisplayName("First name")]
        [Required(ErrorMessage = "First name is required")]
        public string FirstName { get; set; }

        [DisplayName("Last name")]
        [Required(ErrorMessage = "Last name is required")]
        public string LastName { get; set; }

        [Range(1, 120, ErrorMessage = "Invalid Age")]
        public int Age { get; set; }

        [Required(ErrorMessage = "Email is required")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Country is required")]
        [UIHint("CountryDropDown")]
        public string Country { get; set; }
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.pagedesigners.co.nz/2009/08/asp-net-mvc-2-buddy-classes-for-your-models/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC &#8211; Validation Summary with 2 Forms &amp; 1 View</title>
		<link>http://www.pagedesigners.co.nz/2009/07/asp-net-mvc-validation-summary-with-2-forms-1-view/</link>
		<comments>http://www.pagedesigners.co.nz/2009/07/asp-net-mvc-validation-summary-with-2-forms-1-view/#comments</comments>
		<pubDate>Wed, 15 Jul 2009 20:49:14 +0000</pubDate>
		<dc:creator>charles</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net-mvc]]></category>

		<guid isPermaLink="false">http://50.16.228.129/?p=15</guid>
		<description><![CDATA[I currently have a situation where I have two separate actions that rendered the same view and then on this view it has two individual forms which post to the two aforementioned controller actions. Each of the forms have their &#8230; <a href="http://www.pagedesigners.co.nz/2009/07/asp-net-mvc-validation-summary-with-2-forms-1-view/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I currently have a situation where I have two separate actions that rendered the same view and then on this view it has two individual forms which post to the two aforementioned controller actions.</p>
<p>Each of the forms have their own separate ValidationSummary() calls to display their validation errors. But when I posted to either one of these actions and the validation failed, I quickly realised a short coming of the built in ValidationSummary() helper method… you see, it doesn’t have a clue about which form has the errors!</p>
<p>Confused yet? Oddly enough, so am I.</p>
<p>A screen shot should clear things up:</p>
<p><img src="http://media.tumblr.com/tumblr_l8ih4ph70G1qd6iu1.png"/></p>
<p>And the fail:</p>
<p><img src="http://media.tumblr.com/tumblr_l8ih582lbl1qd6iu1.png"/></p>
<p>Making sense now? Good&#8230;</p>
<p>Anyway, I came up with an easy enough work around so I thought I would share it.</p>
<p><!-- more --></p>
<pre class="brush: c-sharp">namespace System.Web.Mvc
{
    public static class HtmlExtensions
    {
        public static string ActionValidationSummary(this HtmlHelper html, string action)
        {
            string currentAction = html.ViewContext.RouteData.Values["action"].ToString();

            if (currentAction.ToLower() == action.ToLower())
                return html.ValidationSummary();

            return string.Empty;
        }
    }
}</pre>
<p>I&#8217;m (basically) calling it like so:</p>
<pre class="brush: xml">&lt;h2&gt;Register&lt;/h2&gt;

&lt;%= Html.ActionValidationSummary("Register") %&gt;

&lt;form method="post" id="register-form" action="&lt;%= Html.AttributeEncode(Url.Action("Register")) %&gt;"&gt;

... blah ...

&lt;/form&gt;

&lt;h2&gt;User Login&lt;/h2&gt;

&lt;%= Html.ActionValidationSummary("LogIn") %&gt;

&lt;form method="post" id="login-form" action="&lt;%= Html.AttributeEncode(Url.Action("LogIn")) %&gt;"&gt;

... blah ...

&lt;/form&gt;</pre>
<p>And that&#8217;s it. Enjoy.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pagedesigners.co.nz/2009/07/asp-net-mvc-validation-summary-with-2-forms-1-view/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
