<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Nick Olsen&#039;s Programming Tips</title>
	<atom:link href="https://nickstips.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://nickstips.wordpress.com</link>
	<description>Just another programmer&#039;s ramblings</description>
	<lastBuildDate>Wed, 23 Dec 2015 02:07:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<site xmlns="com-wordpress:feed-additions:1">11989588</site><cloud domain='nickstips.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://s0.wp.com/i/buttonw-com.png</url>
		<title>Nick Olsen&#039;s Programming Tips</title>
		<link>https://nickstips.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://nickstips.wordpress.com/osd.xml" title="Nick Olsen&#039;s Programming Tips" />
	<atom:link rel='hub' href='https://nickstips.wordpress.com/?pushpress=hub'/>
	<item>
		<title>ASP.NET APIController 500 Internal Server Errors</title>
		<link>https://nickstips.wordpress.com/2015/12/22/asp-net-apicontroller-500-internal-server-errors/</link>
					<comments>https://nickstips.wordpress.com/2015/12/22/asp-net-apicontroller-500-internal-server-errors/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Wed, 23 Dec 2015 02:06:10 +0000</pubDate>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[IIS]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=980</guid>

					<description><![CDATA[I had a situation where locally, calling an APIController method worked fine but when I uploaded the site to an Azure service, every time I called any method I would get back a 500 Internal Server Error.  The project had a mix of standard MVC Controllers and APIControllers and the MVC Controllers worked fine but [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I had a situation where locally, calling an APIController method worked fine but when I uploaded the site to an Azure service, every time I called any method I would get back a 500 Internal Server Error.  The project had a mix of standard MVC Controllers and APIControllers and the MVC Controllers worked fine but the APIControllers crashed every time.  In an attempt to figure out what was going on, I logged into the remote server and checked the IIS logs but found nothing. I could see that 500 error being returned, but got nothing from the logs or the Event Viewer.</p>
<p>In a normal ASP.NET MVC project you could turn off custom errors through the web.config with something like this, but that did not provide any extra information.</p>
<pre>
&lt;<span class="pl-ent">customErrors</span> <span class="pl-e">mode</span>=<span class="pl-s"><span class="pl-pds">"</span>Off<span class="pl-pds">"</span></span> /&gt;
</pre>
<p>After some digging, I found out that in order to return more detailed error messages from an APIController, you have to set the following setting while the application starts.  I dropped this in the Global.asax.cs Application_Start method and it provided the detailed error messages I needed.</p>
<pre></pre>
<p class="p1">GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;</p>
<p class="p1">
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2015/12/22/asp-net-apicontroller-500-internal-server-errors/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">980</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>
	</item>
		<item>
		<title>IE9 Bug: Div height grows on hover when overflow is set to auto</title>
		<link>https://nickstips.wordpress.com/2012/09/21/ie9-bug-div-height-grows-on-hover-when-overflow-is-set-to-auto/</link>
					<comments>https://nickstips.wordpress.com/2012/09/21/ie9-bug-div-height-grows-on-hover-when-overflow-is-set-to-auto/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Fri, 21 Sep 2012 14:25:24 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[ie9]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=971</guid>

					<description><![CDATA[It turns out that if you have a div set to overflow:auto, the contents of that div are wider than the containing div, and you have an element with a :hover css class inside that div that IE9 will start messing with the height of the div whenever the mouse is moved inside it. (see [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>It turns out that if you have a div set to overflow:auto, the contents of that div are wider than the containing div, and you have an element with a :hover css class inside that div that IE9 will start messing with the height of the div whenever the mouse is moved inside it. (see below)</p>
<p><a href="https://nickstips.wordpress.com/wp-content/uploads/2012/09/hover-bug.png"><img class="size-full wp-image" src="https://nickstips.wordpress.com/wp-content/uploads/2012/09/hover-bug.png?w=508" alt="Image" /></a></p>
<p> </p>
<p>The work around for this is quite easy.  All you need to do is specify a height on the wrapper div and set the inner div to a height of 100%.  You can see an example of the problem and the solution <a href="http://jsfiddle.net/Cqs4Z/11/">here</a>.</p>
<p> </p>
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2012/09/21/ie9-bug-div-height-grows-on-hover-when-overflow-is-set-to-auto/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">971</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>

		<media:content url="https://nickstips.wordpress.com/wp-content/uploads/2012/09/hover-bug.png?w=508" medium="image">
			<media:title type="html">Image</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC: LessThan and GreaterThan Validation Attributes</title>
		<link>https://nickstips.wordpress.com/2011/11/05/asp-net-mvc-lessthan-and-greaterthan-validation-attributes/</link>
					<comments>https://nickstips.wordpress.com/2011/11/05/asp-net-mvc-lessthan-and-greaterthan-validation-attributes/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Sat, 05 Nov 2011 19:05:24 +0000</pubDate>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Validation]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=948</guid>

					<description><![CDATA[ASP.NET MVC ships with a handy Compare attribute that allows you to compare two inputs and display a validation message if they do not match. This is great for sign up pages where a password needs to be entered twice and we need to ensure that they are equal but aside from that, I haven&#8217;t [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>ASP.NET MVC ships with a handy Compare attribute that allows you to compare two inputs and display a validation message if they do not match.  This is great for sign up pages where a password needs to be entered twice and we need to ensure that they are equal but aside from that, I haven&#8217;t found any other use for the Compare attribute.  What I have found that I have needed more are LessThan and GreaterThan attributes that allow you to compare two inputs and ensure that one is less than or greater than the other.  The ASP.NET MVC Framework doesn&#8217;t not come loaded with such attributes so using the Compare attribute as a template, I have created them.</p>
<p><a href="https://nickstips.wordpress.com/wp-content/uploads/2011/11/less_than.png"><img data-attachment-id="963" data-permalink="https://nickstips.wordpress.com/2011/11/05/asp-net-mvc-lessthan-and-greaterthan-validation-attributes/less_than/" data-orig-file="https://nickstips.wordpress.com/wp-content/uploads/2011/11/less_than.png" data-orig-size="563,226" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="less_than" data-image-description="" data-image-caption="" data-medium-file="https://nickstips.wordpress.com/wp-content/uploads/2011/11/less_than.png?w=300" data-large-file="https://nickstips.wordpress.com/wp-content/uploads/2011/11/less_than.png?w=563" src="https://nickstips.wordpress.com/wp-content/uploads/2011/11/less_than.png?w=780" alt="" title="less_than"   class="aligncenter size-full wp-image-963" srcset="https://nickstips.wordpress.com/wp-content/uploads/2011/11/less_than.png 563w, https://nickstips.wordpress.com/wp-content/uploads/2011/11/less_than.png?w=150&amp;h=60 150w, https://nickstips.wordpress.com/wp-content/uploads/2011/11/less_than.png?w=300&amp;h=120 300w" sizes="(max-width: 563px) 100vw, 563px" /></a></p>
<p>You can download a project <a href="http://www.box.net/shared/030q97qjex6eun5n7yyx">here</a> that has the complete source code and test pages for these attributes.</p>
<p>We will start first with the validation attribute:</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class NumericLessThanAttribute : ValidationAttribute, IClientValidatable
{
    private const string lessThanErrorMessage = &quot;{0} must be less than {1}.&quot;;
    private const string lessThanOrEqualToErrorMessage = &quot;{0} must be less than or equal to {1}.&quot;;                

    public string OtherProperty { get; private set; }

    private bool allowEquality;

    public bool AllowEquality
    {
        get { return this.allowEquality; }
        set
        {
            this.allowEquality = value;
                
            // Set the error message based on whether or not
            // equality is allowed
            this.ErrorMessage = (value ? lessThanOrEqualToErrorMessage : lessThanErrorMessage);
        }
    }        

    public NumericLessThanAttribute(string otherProperty)
        : base(lessThanErrorMessage)
    {
        if (otherProperty == null) { throw new ArgumentNullException(&quot;otherProperty&quot;); }
        this.OtherProperty = otherProperty;            
    }        

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, this.OtherProperty);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);   
            
        if (otherPropertyInfo == null)
        {
            return new ValidationResult(String.Format(CultureInfo.CurrentCulture, &quot;Could not find a property named {0}.&quot;, OtherProperty));
        }

        object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);

        decimal decValue;
        decimal decOtherPropertyValue;

        // Check to ensure the validating property is numeric
        if (!decimal.TryParse(value.ToString(), out decValue))
        {
            return new ValidationResult(String.Format(CultureInfo.CurrentCulture, &quot;{0} is not a numeric value.&quot;, validationContext.DisplayName));
        }

        // Check to ensure the other property is numeric
        if (!decimal.TryParse(otherPropertyValue.ToString(), out decOtherPropertyValue))
        {
            return new ValidationResult(String.Format(CultureInfo.CurrentCulture, &quot;{0} is not a numeric value.&quot;, OtherProperty));
        }

        // Check for equality
        if (AllowEquality &amp;&amp; decValue == decOtherPropertyValue)
        {
            return null;
        }
        // Check to see if the value is greater than the other property value
        else if (decValue &gt; decOtherPropertyValue)
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }            

        return null;
    }

    public static string FormatPropertyForClientValidation(string property)
    {
        if (property == null)
        {
            throw new ArgumentException(&quot;Value cannot be null or empty.&quot;, &quot;property&quot;);
        }
        return &quot;*.&quot; + property;
    }       

    public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {           
        yield return new ModelClientValidationNumericLessThanRule(FormatErrorMessage(metadata.DisplayName), FormatPropertyForClientValidation(this.OtherProperty), this.AllowEquality);
    }
}
</pre>
<p>Like the compare attribute, this attribute will compare against another value on the form.  The other property name is passed into the attributes constructor.  There is also another named parameter, AllowEquality, which allows you to specify whether or not the value being validated can be equal to the &#8216;other&#8217; property.  The IsValid method is pretty straightforward and compares the two values to see if they are valid.</p>
<p>The last method, GetClientValidationRules creates a ModelClientValidationNumericLessThanRule class defined below:</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class ModelClientValidationNumericLessThanRule : ModelClientValidationRule
{
    public ModelClientValidationNumericLessThanRule(string errorMessage, object other, bool allowEquality)
    {
        ErrorMessage = errorMessage;
        ValidationType = &quot;numericlessthan&quot;;
        ValidationParameters[&quot;other&quot;] = other;
        ValidationParameters[&quot;allowequality&quot;] = allowEquality;
    }
}
</pre>
<p>This class specifies the client validation type and parameters that will be loaded into the data attributes of the input on the html page.  Here we have specified that the jQuery client validation type has a name of &#8216;numericlessthan&#8217; and that it will accept to parameters values named &#8216;other&#8217; and &#8216;allowEquality&#8217;.</p>
<p>Now that we have created these two classes, we can now generate a model to test the validation:</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class NumericLessThanViewModel
{
    public decimal MaxValue { get; set; }

    [NumericLessThan(&quot;MaxValue&quot;, AllowEquality = true)]
    [Display(Name=&quot;Value&quot;)]
    public decimal Value { get; set; }
}
</pre>
<p>For this to work we need at least two properties on the model; one that specifies the maximum value and another that will be used for the user input.  On the user input property, add the NumericLessThan attribute and specify the name of the &#8216;other&#8217; property to which it will be compared and whether or not equality is allowed.  The &#8216;other&#8217; value will usually be loaded as a hidden field in the form.</p>
<p>At this point just the server side validation has been setup.  We need to add a javascript file as well to enable client side validation.</p>
<pre class="brush: jscript; title: ; wrap-lines: false; notranslate">
jQuery.validator.addMethod('numericlessthan', function (value, element, params) {
    var otherValue = $(params.element).val();

    return isNaN(value) &amp;&amp; isNaN(otherValue) || (params.allowequality === 'True' ? parseFloat(value) &lt;= parseFloat(otherValue) : parseFloat(value) &lt; parseFloat(otherValue));
}, '');

jQuery.validator.unobtrusive.adapters.add('numericlessthan', ['other', 'allowequality'], function (options) {
    var prefix = options.element.name.substr(0, options.element.name.lastIndexOf('.') + 1),
    other = options.params.other,
    fullOtherName = appendModelPrefix(other, prefix),
    element = $(options.form).find(':input[name=' + fullOtherName + ']')[0];

    options.rules['numericlessthan'] = { allowequality: options.params.allowequality, element: element };
    if (options.message) {
        options.messages['numericlessthan'] = options.message;
    }
});

function appendModelPrefix(value, prefix) {
    if (value.indexOf('*.') === 0) {
        value = value.replace('*.', prefix);
    }
    return value;
}
</pre>
<p>The first method in the code above adds the actual method that is called when validating the input.  In it we check to see if both values are numbers and depending on whether or not we specified to allow equality, we check to ensure that the user input is less than or equal to the other value.</p>
<p>The second method adds the rule to the set of jQuery validation adapters and supplies the wiring up of the parameters that will be supplied to the validation method.</p>
<p>And that is it.  The ASP.NET MVC framework and the jQuery validation libraries will take care of the rest.  </p>
<p>In the downloadable project above I have included a NumericGreaterThan attribute as well but as you can image, the code is almost identical to the LessThan attribute so I will not be going over it here.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2011/11/05/asp-net-mvc-lessthan-and-greaterthan-validation-attributes/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">948</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>

		<media:content url="https://nickstips.wordpress.com/wp-content/uploads/2011/11/less_than.png" medium="image">
			<media:title type="html">less_than</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC: Displaying Client and Server Side Validation Using Error Icons</title>
		<link>https://nickstips.wordpress.com/2011/08/23/asp-net-mvc-displaying-client-and-server-side-validation-using-error-icons/</link>
					<comments>https://nickstips.wordpress.com/2011/08/23/asp-net-mvc-displaying-client-and-server-side-validation-using-error-icons/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Tue, 23 Aug 2011 23:48:33 +0000</pubDate>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Client Side Validation]]></category>
		<category><![CDATA[jQuery UI]]></category>
		<category><![CDATA[qTip]]></category>
		<category><![CDATA[Server Side Validation]]></category>
		<category><![CDATA[Validation]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=941</guid>

					<description><![CDATA[In a previous post I showed how you could display both client and server side validation using qTip tooltips. In this post I will show how you can display an error icon next to the field that is invalid and then when the user hovers over the icon, display the error message (demonstrated below). As [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In a previous <a href="https://nickstips.wordpress.com/2011/08/18/asp-net-mvc-displaying-client-and-server-side-validation-using-qtip-tooltips/">post</a> I showed how you could display both client and server side validation using qTip tooltips.  In this post I will show how you can display an error icon next to the field that is invalid and then when the user hovers over the icon, display the error message (demonstrated below).</p>
<p><a href="https://nickstips.wordpress.com/wp-content/uploads/2011/08/example.png"><img data-attachment-id="943" data-permalink="https://nickstips.wordpress.com/2011/08/23/asp-net-mvc-displaying-client-and-server-side-validation-using-error-icons/example-2/" data-orig-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/example.png" data-orig-size="436,405" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="example" data-image-description="" data-image-caption="" data-medium-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/example.png?w=300" data-large-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/example.png?w=436" src="https://nickstips.wordpress.com/wp-content/uploads/2011/08/example.png?w=780" alt="" title="example"   class="aligncenter size-full wp-image-943" srcset="https://nickstips.wordpress.com/wp-content/uploads/2011/08/example.png 436w, https://nickstips.wordpress.com/wp-content/uploads/2011/08/example.png?w=150&amp;h=139 150w, https://nickstips.wordpress.com/wp-content/uploads/2011/08/example.png?w=300&amp;h=279 300w" sizes="(max-width: 436px) 100vw, 436px" /></a></p>
<p>As done previously I will be using the same example project from <a href="https://nickstips.wordpress.com/2011/08/11/asp-net-mvc-ajax-dialog-form-using-jquery-ui/">this post</a> where we created a dialog form which was submitted via Ajax.</p>
<p>You can download the complete solution for this example <a href="http://www.box.net/shared/yvi89clb8x3e6ejrclzo">here</a>.</p>
<p>First, the error icon.  I utilized the ui-icon-alert class that comes with jQuery UI to display the error icon.  But, to get the icon to display correctly without having to create a containing div element around the icon, we need to add a new class to the jquery.ui.theme.css file.  Open up the default jquery.ui.theme.css file or if you have added a custom theme, the jquery-ui-[version number].custom.css file and find the states and images sub section under the Icons section. Add the following css class to the list of classes there.</p>
<pre class="brush: css; title: ; wrap-lines: false; notranslate">
.ui-state-error-icon { display:inline-block;  width: 16px; height: 16px; background-image: url(images/ui-icons_cd0a0a_256x240.png);  }
</pre>
<p>This class will allow a 16 x 16px icon from the error images png to be displayed in an empty element.</p>
<p>Next we need to change the onError function in the jquery.validate.unobtrusive.js javascript file.  Open that file and replace the onError function with that shown below.</p>
<pre class="brush: jscript; title: ; wrap-lines: false; notranslate">
function onError(error, inputElement) {  // 'this' is the form element        
    var container = $(this).find(&quot;[data-valmsg-for='&quot; + inputElement[0].name + &quot;']&quot;),
    replace = $.parseJSON(container.attr(&quot;data-valmsg-replace&quot;)) !== false;

    container.removeClass(&quot;field-validation-valid&quot;).addClass(&quot;field-validation-error&quot;);
    error.data(&quot;unobtrusiveContainer&quot;, container);

    if (replace) {
            
        // Do not display the error message
        //container.empty();
        //error.removeClass(&quot;input-validation-error&quot;).appendTo(container);

        // If the error message is an empty string, remove the classes
        // from the container that displays the error icon.  Otherwise
        // Add the classes necessary to display the error icon and
        // wire up the qTip tooltip for the container
        if ($(error).text() == &quot;&quot;) {
            container.removeClass(&quot;ui-state-error-icon&quot;).removeClass(&quot;ui-icon-alert&quot;);
        }
        else {
            container.addClass(&quot;ui-state-error-icon&quot;).addClass(&quot;ui-icon-alert&quot;);

            $(container).qtip({
                overwrite: true,
                content: $(error).text(),
                style: {
                    classes: 'ui-tooltip-red'
                }
            });
        }
    }
    else {
        error.hide();
    }
}
</pre>
<p>Here instead of displaying the error message in associated container, we are displaying the alert icon and wiring up a qTip tooltip to display the error text.  (Make sure in your Layout or MasterPage that you reference the jquery.validate.unobtrusive.js javascript file not the jquery.validate.unobtrusive.<em>min</em>.js file.)</p>
<p>If you run the application now all client side errors will be displayed using little error icons as pictured above and if the user hovers over the icon, the error message will be displayed in the tooltip.</p>
<p>To make server side validation messages appear in the same way we need to add another javascript function to each page.  Create a new javascript file named jquer.qtip.validation.js and paste the following code into it.</p>
<pre class="brush: jscript; title: ; wrap-lines: false; notranslate">
$(function () {
    // Run this function for all validation error messages
    $('.field-validation-error').each(function () {

        // Get the error text to be displayed
        var errorText = $(this).text();

        // Remove the text from the error message span
        // element and add the classes to display the icon
        $(this).empty();
        $(this).addClass(&quot;ui-state-error-icon&quot;).addClass(&quot;ui-icon-alert&quot;);

        // Wire up the tooltip to display the error message
        $(this).qtip({
            overwrite: true,
            content: errorText,
            style: {
                classes: 'ui-tooltip-red'
            }
        });     
    });
});    
</pre>
<p>Here we are doing the same thing we did for client side validation except we are iterating over all elements with the field-validation-error class and removing its text, displaying the icon, and placing the error message in the tooltip.  Make sure that on every form where you have server side validation displayed that you reference the jquery.qtip.validation.js javascript file.</p>
<p>There you have it.  Client and server side validation displayed using error icons and tooltips.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2011/08/23/asp-net-mvc-displaying-client-and-server-side-validation-using-error-icons/feed/</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">941</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>

		<media:content url="https://nickstips.wordpress.com/wp-content/uploads/2011/08/example.png" medium="image">
			<media:title type="html">example</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC: Internal Server Error (500) on Action Method Returning Json Result</title>
		<link>https://nickstips.wordpress.com/2011/08/20/asp-net-mvc-internal-server-error-500-on-action-method-returning-json-result/</link>
					<comments>https://nickstips.wordpress.com/2011/08/20/asp-net-mvc-internal-server-error-500-on-action-method-returning-json-result/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Sat, 20 Aug 2011 20:31:42 +0000</pubDate>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Json]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=937</guid>

					<description><![CDATA[The ASP.NET MVC framework allows you to easily return Json from an action method. This makes jQuery Ajax calls very easy to implement, as shown below. The JavaScript The Action Method There is only one problem with the above action method. If you attempt to run it, the call to the ActionMethod will result in [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>The ASP.NET MVC framework allows you to easily return Json from an action method.  This makes jQuery Ajax calls very easy to implement, as shown below.</p>
<p><strong>The JavaScript</strong></p>
<pre class="brush: jscript; title: ; notranslate">
$(.button).getJSON('/Home/GetJsonData', 
                   { id = 34 },
                   function(data) {
                      // Do something with it
                   }
);
</pre>
<p><strong>The Action Method</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public ActionResult GetJsonData(int id)
{
     Person person = this.personService.GetPerson(id);     
     return Json(person);
}
</pre>
<p>There is only one problem with the above action method.  If you attempt to run it, the call to the ActionMethod will result in a Internal Server Error (Error 500).  The reason is that by default data can only be retrieved using a POST operation if your action method returns a Json result.  To make this work with a GET request, all you need to use is the overloaded Json() method shown below. </p>
<pre class="brush: csharp; title: ; notranslate">
public ActionResult GetJsonData(int id)
{
     Person person = this.personService.GetPerson(id);     
     return Json(person, JsonRequestBehavior.AllowGet);
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2011/08/20/asp-net-mvc-internal-server-error-500-on-action-method-returning-json-result/feed/</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">937</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC: Displaying Client and Server Side Validation Using qTip Tooltips</title>
		<link>https://nickstips.wordpress.com/2011/08/18/asp-net-mvc-displaying-client-and-server-side-validation-using-qtip-tooltips/</link>
					<comments>https://nickstips.wordpress.com/2011/08/18/asp-net-mvc-displaying-client-and-server-side-validation-using-qtip-tooltips/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Fri, 19 Aug 2011 00:06:44 +0000</pubDate>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Client Side Validation]]></category>
		<category><![CDATA[qTip]]></category>
		<category><![CDATA[Server Side Validation]]></category>
		<category><![CDATA[Validation]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=909</guid>

					<description><![CDATA[The ASP.NET MVC framework makes it very easy to do both client and server side validation out of the box. Using DataAnnotations on your model properties the framework can display errors to the user client side using jQuery validation or for more complex situations, model errors can be returned using server side validation. Here is [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>The ASP.NET MVC framework makes it very easy to do both client and server side validation out of the box.  Using DataAnnotations on your model properties the framework can display errors to the user client side using jQuery validation or for more complex situations, model errors can be returned using server side validation.  Here is an example of a model and corresponding error messages that are displayed to the user on offending fields.</p>
<p><a href="https://nickstips.wordpress.com/wp-content/uploads/2011/08/model.png"><img data-attachment-id="910" data-permalink="https://nickstips.wordpress.com/2011/08/18/asp-net-mvc-displaying-client-and-server-side-validation-using-qtip-tooltips/model/" data-orig-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/model.png" data-orig-size="697,436" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="model" data-image-description="" data-image-caption="" data-medium-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/model.png?w=300" data-large-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/model.png?w=697" src="https://nickstips.wordpress.com/wp-content/uploads/2011/08/model.png?w=780" alt="" title="model"   class="aligncenter size-full wp-image-910" srcset="https://nickstips.wordpress.com/wp-content/uploads/2011/08/model.png 697w, https://nickstips.wordpress.com/wp-content/uploads/2011/08/model.png?w=150&amp;h=94 150w, https://nickstips.wordpress.com/wp-content/uploads/2011/08/model.png?w=300&amp;h=188 300w" sizes="(max-width: 697px) 100vw, 697px" /></a></p>
<p>With the [Required] DataAnnotation on the NickName property we get the error message &#8220;The Nick name field is required&#8221; if the user leaves it blank.  Also, the framework realizes that the Age property is an integer and thus if the user enters a value other than a numeric value, it will display and error message.</p>
<p>The functionality is great but the way in which the error messages are displayed is not very aesthetically pleasing.  Also, when fields are validated on the client side, if you haven&#8217;t built in spaces for the validation text, your form will jump all over the place to make room for the messages.  In an effort to make things a little more pleasing to the eye and to avoid unnecessary form re-sizing I&#8217;m going to show how you can display both client and server side validation in tooltips using the jQuery plugin <a href="http://craigsworks.com/projects/qtip2/">qTip</a>. Our goal is to transfer the form displayed above into the following:</p>
<p><a href="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-validation.png"><img loading="lazy" data-attachment-id="926" data-permalink="https://nickstips.wordpress.com/2011/08/18/asp-net-mvc-displaying-client-and-server-side-validation-using-qtip-tooltips/qtip-validation/" data-orig-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-validation.png" data-orig-size="487,397" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="qtip-validation" data-image-description="" data-image-caption="" data-medium-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-validation.png?w=300" data-large-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-validation.png?w=487" src="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-validation.png?w=780" alt="" title="qtip-validation"   class="aligncenter size-full wp-image-926" srcset="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-validation.png 487w, https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-validation.png?w=150&amp;h=122 150w, https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-validation.png?w=300&amp;h=245 300w" sizes="(max-width: 487px) 100vw, 487px" /></a></p>
<p>You can download the complete solution for this example <a href="http://www.box.net/shared/bg6klmd5cpkdq20rifct">here</a>.</p>
<p>I will be building off of the example from my <a href="https://nickstips.wordpress.com/2011/08/11/asp-net-mvc-ajax-dialog-form-using-jquery-ui/">last post</a> that showed how to use jQuery UI to build Ajax forms.</p>
<p>The first thing you need to do is <a href="http://craigsworks.com/projects/qtip2/download">download</a> the qTip library, add them to your project, and add references to the jquery.qtip.min.js script and jquery.qtip.css style sheet in your _Layout.cshtml or MasterPage.aspx.</p>
<p>The displaying of client side validation errors is handled in the jquery.validate.unobtrusive.js onError method.  We need to alter that method to display the tooltip with the validation message instead of showing the default label.  I cannot take credit for figuring out this code.  I actually am using the technique presented <a href="http://stackoverflow.com/questions/6802045/integrating-qtip-with-mvc3-and-jquery-validation-errorplacement">here</a> with a minor tweak.  Open up the jquery.validate.unobtrusive.js script and replace the onError method with the following:</p>
<pre class="brush: jscript; title: ; wrap-lines: false; notranslate">
function onError(error, inputElement) {  // 'this' is the form element        
    var container = $(this).find(&quot;[data-valmsg-for='&quot; + inputElement[0].name + &quot;']&quot;),
    replace = $.parseJSON(container.attr(&quot;data-valmsg-replace&quot;)) !== false;

    // Remove the following line so the default validation messages are not displayed        
    // container.removeClass(&quot;field-validation-valid&quot;).addClass(&quot;field-validation-error&quot;);

    error.data(&quot;unobtrusiveContainer&quot;, container);

    if (replace) {
        container.empty();
        error.removeClass(&quot;input-validation-error&quot;).appendTo(container);
    }
    else {
        error.hide();
    }

    /**** Added code to display the error message in a qTip tooltip ****/        
    // Set positioning based on the elements position in the form
    var elem = $(inputElement),
        corners = ['left center', 'right center'],
        flipIt = elem.parents('span.right').length &gt; 0;

    // Check we have a valid error message
    if (!error.is(':empty')) {
        // Apply the tooltip only if it isn't valid
        elem.filter(':not(.valid)').qtip({
            overwrite: false,
            content: error,
            position: {
                my: corners[flipIt ? 0 : 1],
                at: corners[flipIt ? 1 : 0],
                viewport: $(window)
            },                
            show: {
                event: false,
                ready: true
            },
            hide: false,
            style: {
                classes: 'ui-tooltip-red' // Make it red... the classic error colour!
            }
        })

        // If we have a tooltip on this element already, just update its content
        .qtip('option', 'content.text', error);
    }

    // If the error is empty, remove the qTip
    else { elem.qtip('destroy'); }
}
</pre>
<p>Take a look at the qTip <a href="http://craigsworks.com/projects/qtip2/docs/">documentation</a> for more information on what each of the options are doing here.</p>
<p>Your site is probably referencing the jquery.validate.unobtrusive.<em>min</em>.js file so make sure you replace that reference with the non-minified version you just updated.</p>
<p>Next, we need to update the DialogForm.js script file we created to do two things when the dialog window is closed; remove all the qTip tooltips and remove the form from the page after it is submitted.  It turns out that when closing a jQuery UI dialog window, the constructed elements are not actually removed from the page but rather just hidden.  After a successful ajax post and reload of the form, there will be issues rendering the server side validation messages if we don&#8217;t remove the submitted form.  That is why the form has to be removed when the dialog is closed.</p>
<p>To make these changes, open the DialogForm.js file and add the close function to the dialog generation function.</p>
<pre class="brush: jscript; title: ; wrap-lines: false; notranslate">
$(function () {
    // Wire up the click event of any dialog links
    $('.dialogLink').live('click', function () {
        var element = $(this);

        // Retrieve values from the HTML5 data attributes of the link        
        var dialogTitle = element.attr('data-dialog-title');
        var updateTargetId = '#' + element.attr('data-update-target-id');
        var updateUrl = element.attr('data-update-url');
        
        // Generate a unique id for the dialog div
        var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
        var dialogDiv = &quot;&lt;div id='&quot; + dialogId + &quot;'&gt;&lt;/div&gt;&quot;;

        // Load the form into the dialog div
        $(dialogDiv).load(this.href, function () {
            $(this).dialog({
                modal: true,
                resizable: false,
                title: dialogTitle,
                buttons: {
                    &quot;Save&quot;: function () {
                        // Manually submit the form                        
                        var form = $('form', this);
                        $(form).submit();
                    },
                    &quot;Cancel&quot;: function () {
                        $(this).dialog('close');
                    }
                },
                // **** START NEW CODE ****
                close: function () {
                    // Remove all qTip tooltips
                    $('.qtip').remove();

                    // It turns out that closing a jQuery UI dialog
                    // does not actually remove the element from the
                    // page but just hides it. For the server side 
                    // validation tooltips to show up you need to
                    // remove the original form the page
                    $('#' + dialogId).remove();
                }
                // **** END NEW CODE ****
            });

            // Enable client side validation
            $.validator.unobtrusive.parse(this);

            // Setup the ajax submit logic
            wireUpForm(this, updateTargetId, updateUrl);
        });
        return false;
    });
});
</pre>
<p>If we run the application at this point then the client side validation messages will be displayed in the qTip tooltips.  Now, to display the server side validation messages in qTip tooltips as well.</p>
<p>To demonstrate how to do this I am going to create a custom validation attribute named AgeValidation and add it to our Profile model.  This validation can actually be done client side but I want to show how to show the tooltips after a server side validation error, so humor me.</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class Profile
{
    [Required]
    public string Name { get; set; }

    [Required]
    [StringLength(10, MinimumLength=3)]
    [Display(Name=&quot;Nick name&quot;)]
    public string NickName { get; set; }

    [Required]        
    public string Email { get; set; }

    [Required]
    [AgeValidation(ErrorMessage=&quot;You must be older than 12 to sign up&quot;)]
    public int Age { get; set; }
}

// I know this can be accomplished using the Range validation
// attribute but I have implmented it as a custom validation
// attribute to show how server side validation error messages
// can be displayed using qTip tooltips
public class AgeValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null)
            return false;

        int intValue;
        if (!int.TryParse(value.ToString(), out intValue))
            return false;

        return (intValue &gt; 12);
    }
}
</pre>
<p>Now if the user attempts to submit a Profile model with an age less than 12, a server side validation error message will be added.  The trick to displaying the server side validation errors in qTip tooltips is to know how ASP.NET MVC renders the default label with the error message.  It turns out that when a validation error message is displayed, ASP.NET MVC creates a span element with the class &#8216;field-validation-error&#8217; and its contents contain the error message.  So, in order to display that message in a tooltip, all we need to do is extract that error message from the span element and load it into a tootip.  This can be accomplished by the following javascript function:</p>
<pre class="brush: jscript; title: ; wrap-lines: false; notranslate">
$(function () {
    // Run this function for all validation error messages
    $('.field-validation-error').each(function () {
        // Get the name of the element the error message is intended for
        // Note: ASP.NET MVC replaces the '[', ']', and '.' characters with an
        // underscore but the data-valmsg-for value will have the original characters
        var inputElem = '#' + $(this).attr('data-valmsg-for').replace('.', '_').replace('[', '_').replace(']', '_');

        var corners = ['left center', 'right center'];
        var flipIt = $(inputElem).parents('span.right').length &gt; 0;

        // Hide the default validation error
        $(this).hide();

        // Show the validation error using qTip
        $(inputElem).filter(':not(.valid)').qtip({
            content: { text: $(this).text() }, // Set the content to be the error message
            position: {            
                my: corners[flipIt ? 0 : 1],
                at: corners[flipIt ? 1 : 0],
                viewport: $(window)
            },
            show: { ready: true },
            hide: false,
            style: { classes: 'ui-tooltip-red' }
        });       
    });
});    
</pre>
<p>And lastly, we need to add a reference to the above script on the page that will display the form fields for the Profile model.</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
@model DialogFormExample.Models.Profile

@using (Html.BeginForm()) {    
        &lt;div class=&quot;editor-label&quot;&gt;
            @Html.LabelFor(model =&gt; model.Name)
        &lt;/div&gt;
        &lt;div class=&quot;editor-field&quot;&gt;
            @Html.EditorFor(model =&gt; model.Name)&lt;br /&gt;
            @Html.ValidationMessageFor(model =&gt; model.Name)
        &lt;/div&gt;

        &lt;div class=&quot;editor-label&quot;&gt;
            @Html.LabelFor(model =&gt; model.NickName)
        &lt;/div&gt;
        &lt;div class=&quot;editor-field&quot;&gt;
            @Html.EditorFor(model =&gt; model.NickName) &lt;br /&gt;
            @Html.ValidationMessageFor(model =&gt; model.NickName)
        &lt;/div&gt;

        &lt;div class=&quot;editor-label&quot;&gt;
            @Html.LabelFor(model =&gt; model.Email)
        &lt;/div&gt;
        &lt;div class=&quot;editor-field&quot;&gt;
            @Html.EditorFor(model =&gt; model.Email) &lt;br /&gt;
            @Html.ValidationMessageFor(model =&gt; model.Email)
        &lt;/div&gt;

        &lt;div class=&quot;editor-label&quot;&gt;
            @Html.LabelFor(model =&gt; model.Age)
        &lt;/div&gt;
        &lt;div class=&quot;editor-field&quot;&gt;
            @Html.EditorFor(model =&gt; model.Age) &lt;br /&gt;
            @Html.ValidationMessageFor(model =&gt; model.Age)
        &lt;/div&gt;    
}
  
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery.qtip.validation.js&quot;)&quot; type=&quot;text/javascript&quot; /&gt;
</pre>
<p>And that&#8217;s it.  Now you have a form that will display both server and client side validation in qTip tooltips!</p>
<p><a href="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-server-validation.png"><img loading="lazy" data-attachment-id="933" data-permalink="https://nickstips.wordpress.com/2011/08/18/asp-net-mvc-displaying-client-and-server-side-validation-using-qtip-tooltips/qtip-server-validation/" data-orig-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-server-validation.png" data-orig-size="508,393" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="qtip-server-validation" data-image-description="" data-image-caption="" data-medium-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-server-validation.png?w=300" data-large-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-server-validation.png?w=508" src="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-server-validation.png?w=780" alt="" title="qtip-server-validation"   class="aligncenter size-full wp-image-933" srcset="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-server-validation.png 508w, https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-server-validation.png?w=150&amp;h=116 150w, https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-server-validation.png?w=300&amp;h=232 300w" sizes="(max-width: 508px) 100vw, 508px" /></a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2011/08/18/asp-net-mvc-displaying-client-and-server-side-validation-using-qtip-tooltips/feed/</wfw:commentRss>
			<slash:comments>35</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">909</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>

		<media:content url="https://nickstips.wordpress.com/wp-content/uploads/2011/08/model.png" medium="image">
			<media:title type="html">model</media:title>
		</media:content>

		<media:content url="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-validation.png" medium="image">
			<media:title type="html">qtip-validation</media:title>
		</media:content>

		<media:content url="https://nickstips.wordpress.com/wp-content/uploads/2011/08/qtip-server-validation.png" medium="image">
			<media:title type="html">qtip-server-validation</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC: Client Side Validation with an Ajax Loaded Form</title>
		<link>https://nickstips.wordpress.com/2011/08/13/asp-net-mvc-client-side-validation-with-an-ajax-loaded-form/</link>
					<comments>https://nickstips.wordpress.com/2011/08/13/asp-net-mvc-client-side-validation-with-an-ajax-loaded-form/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Sat, 13 Aug 2011 15:28:57 +0000</pubDate>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Client Side Validation]]></category>
		<category><![CDATA[Validation]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=905</guid>

					<description><![CDATA[In my last post I discussed how to perform some CRUD operations using Ajax and the jQuery UI dialog window. In that posted I included a little gem which I did not point out and probably should have. The ASP.NET MVC framework provides client side validation using the jQuery validation library. It is a great [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In my <a href="https://nickstips.wordpress.com/2011/08/11/asp-net-mvc-ajax-dialog-form-using-jquery-ui/" target="_blank">last post</a> I discussed how to perform some CRUD operations using Ajax and the jQuery UI dialog window.  In that posted I included a little gem which I did not point out and probably should have.</p>
<p>The ASP.NET MVC framework provides client side validation using the jQuery validation library.  It is a great tool for the user as they receive immediate notification when they have entered an invalid value but it is also great for the developer as you reduce unnecessary load on the server.  The problem is all the client side validation logic is setup when the page is loaded so if you load a form using Ajax after the original page has been loaded, client side validation will not work for that form.</p>
<p>In order to remedy this all you need to do is make a manual call to the jQuery validation scripts passing in a selector that will include the form you load.  Here is the line that needs to be included:</p>
<pre class="brush: jscript; title: ; notranslate">

// Enable client side validation
$.validator.unobtrusive.parse('form');

</pre>
<p>Above I have indicated that I want the jQuery validation library to parse all form elements but if you form has been given an id, you can pass in the id of the form as well.  Below is a more complete example from my last post that shows the form being loaded into the dialog window and then the call to the jQuery validation library.</p>
<pre class="brush: jscript; title: ; notranslate">
// Load the form into the dialog div
$(dialogId).load(this.href, function () {
	$(this).dialog({
		modal: true,
		resizable: false,
		title: dialogTitle,
		buttons: {
			&quot;Save&quot;: function () {
				// Manually submit the form
				var form = $('form', this);
				$(form).submit();
			},
			&quot;Cancel&quot;: function () { $(this).dialog('close'); }
		}
	});

	// Enable client side validation
	$.validator.unobtrusive.parse(this);
});
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2011/08/13/asp-net-mvc-client-side-validation-with-an-ajax-loaded-form/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">905</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC: Ajax Dialog Form Using jQuery UI</title>
		<link>https://nickstips.wordpress.com/2011/08/11/asp-net-mvc-ajax-dialog-form-using-jquery-ui/</link>
					<comments>https://nickstips.wordpress.com/2011/08/11/asp-net-mvc-ajax-dialog-form-using-jquery-ui/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Fri, 12 Aug 2011 05:22:06 +0000</pubDate>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[dialog]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[jQuery UI]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=880</guid>

					<description><![CDATA[In one of my recent projects I needed to display some information, allow the user to edit it utilizing a dialog window, post the updated information and reload it for the user using Ajax. I needed to perform the named operations for multiple models so I set out to create some generic code that could [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In one of my recent projects I needed to display some information, allow the user to edit it utilizing a dialog window, post the updated information and reload it for the user using Ajax.  I needed to perform the named operations for multiple models so I set out to create some generic code that could be reused over and over.  Below is a picture of what I am trying to accomplish.</p>
<p><a href="https://nickstips.wordpress.com/wp-content/uploads/2011/08/dialog_form.png"><img loading="lazy" data-attachment-id="895" data-permalink="https://nickstips.wordpress.com/2011/08/11/asp-net-mvc-ajax-dialog-form-using-jquery-ui/dialog_form/" data-orig-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/dialog_form.png" data-orig-size="714,423" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="dialog_form" data-image-description="" data-image-caption="" data-medium-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/dialog_form.png?w=300" data-large-file="https://nickstips.wordpress.com/wp-content/uploads/2011/08/dialog_form.png?w=714" src="https://nickstips.wordpress.com/wp-content/uploads/2011/08/dialog_form.png?w=780" alt="" title="dialog_form"   class="aligncenter size-full wp-image-895" /></a></p>
<p>The project used for the post below can be downloaded <a href="http://www.box.net/shared/5il2su990tb4otgte5hv" target="_blank">here</a>.</p>
<p>First, the model.  For this example, we will use a simple model that contains some profile information for a user.</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class Profile
{
    [Required]
    public string Name { get; set; }

    [Required]
    [StringLength(10, MinimumLength=3)]
    [Display(Name=&quot;Nick name&quot;)]
    public string NickName { get; set; }

    [Required]        
    public string Email { get; set; }

    [Required]
    public int Age { get; set; }
}
</pre>
<p>Second, we need to create three action methods. One will be used to display the profile information, another to display the form for editing the profile, and lastly another that will be used to save the edited profile object.  The first two should always return a PartialView as each of these action methods will be called using Ajax and their result will be loaded into div elements; the first into a div used to display the saved profile and the second into the edit dialog.  The third action method will return a PartialView if the ModelState is invalid so that the errors can be displayed to the user and a Json result indicating the save was successful if all went well.  (Note that in this example I am just storing the profile information in Session but obviously this would be stored in a database or some other data store.)</p>
<pre class="brush: csharp; title: ; notranslate">
public ActionResult Profile()
{
    Profile profile = new Profile();

    // Retrieve the perviously saved Profile
    if (Session[&quot;Profile&quot;] != null)
        profile = Session[&quot;Profile&quot;] as Profile;

    return PartialView(profile);
}

public ActionResult EditProfile()
{
    Profile profile = new Profile();

    // Retrieve the perviously saved Profile
    if (Session[&quot;Profile&quot;] != null)
        profile = Session[&quot;Profile&quot;] as Profile;

    return PartialView(profile);
}

[HttpPost]
public ActionResult EditProfile(Profile profile)
{
    // If the ModelState is invalid then return
    // a PartialView passing in the Profile object
    // with the ModelState errors
    if (!ModelState.IsValid)
        return PartialView(&quot;EditProfile&quot;, profile);

    // Store the Profile object and return
    // a Json result indicating the Profile 
    // has been saved
    Session[&quot;Profile&quot;] = profile;
    return Json(new { success = true });            
}
</pre>
<p>Next we need to create the two partial views that correspond to the first two action methods we created above.  In this example, the partial view for the EditProfile action is pretty much just the stock view created by the MVC frameowork except I have removed the input element to submit the form as we will use the buttons on the jQuery UI dialog to submit it.</p>
<p>The second partial view, the one that displays the saved Profile object again in this example is the stock view with a few added elements.</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
@using DialogFormExample.MvcHelpers

@model DialogFormExample.Models.Profile

&lt;fieldset&gt;
    &lt;legend&gt;Contact Info&lt;/legend&gt;
    
    &lt;div class=&quot;display-field&quot;&gt;
        Name: @Html.DisplayFor(model =&gt; model.Name)
    &lt;/div&gt;

    &lt;div class=&quot;display-field&quot;&gt;
        Nick name: @Html.DisplayFor(model =&gt; model.NickName)
    &lt;/div&gt;
    
    &lt;div class=&quot;display-field&quot;&gt;
        Email: @Html.DisplayFor(model =&gt; model.Email)
    &lt;/div&gt;
    
    &lt;div class=&quot;display-field&quot;&gt;
        Age: @Html.DisplayFor(model =&gt; model.Age)
    &lt;/div&gt;

    &lt;div class=&quot;right&quot;&gt;
        @Html.DialogFormLink(&quot;Edit&quot;, Url.Action(&quot;EditProfile&quot;), &quot;Edit Profile&quot;, &quot;ProfileContainer&quot;, Url.Action(&quot;Profile&quot;))
    &lt;/div&gt;
&lt;/fieldset&gt;
</pre>
<p>The first portion of the partial view just displays the form elements required for editing the model.  This is just the stock Edit view modified only slightly.  The new code starts at line 25.  Here I created an extension method for HtmlHelper named DialogFormLink that will create an anchor tag loaded with all the needed information to make the dialog form work.  Here is the code for the extension method.  You can read the comments to get an understanding of the parameters it requires.</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
/// &lt;summary&gt;
/// Creates a link that will open a jQuery UI dialog form.
/// &lt;/summary&gt;
/// &lt;param name=&quot;htmlHelper&quot;&gt;&lt;/param&gt;
/// &lt;param name=&quot;linkText&quot;&gt;The inner text of the anchor element&lt;/param&gt;
/// &lt;param name=&quot;dialogContentUrl&quot;&gt;The url that will return the content to be loaded into the dialog window&lt;/param&gt;
/// &lt;param name=&quot;dialogTitle&quot;&gt;The title to be displayed in the dialog window&lt;/param&gt;
/// &lt;param name=&quot;updateTargetId&quot;&gt;The id of the div that should be updated after the form submission&lt;/param&gt;
/// &lt;param name=&quot;updateUrl&quot;&gt;The url that will return the content to be loaded into the traget div&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public static MvcHtmlString DialogFormLink(this HtmlHelper htmlHelper, string linkText, string dialogContentUrl,
    string dialogId, string dialogTitle, string updateTargetId, string updateUrl)
{
    TagBuilder builder = new TagBuilder(&quot;a&quot;);
    builder.SetInnerText(linkText);
    builder.Attributes.Add(&quot;href&quot;, dialogContentUrl);            
    builder.Attributes.Add(&quot;data-dialog-title&quot;, dialogTitle);
    builder.Attributes.Add(&quot;data-update-target-id&quot;, updateTargetId);
    builder.Attributes.Add(&quot;data-update-url&quot;, updateUrl);

    // Add a css class named dialogLink that will be
    // used to identify the anchor tag and to wire up
    // the jQuery functions
    builder.AddCssClass(&quot;dialogLink&quot;);

    return new MvcHtmlString(builder.ToString());
}   
</pre>
<p>The above extension method that builds our anchor tag utilizes the HTML5 data attributes to store information such as the title of the dialog window,  the url that will return the content of the dialog window, the id of the div to update after the form is submitted, and the url that will update the target div.</p>
<p>Now we need to add the container div to hold the Profile information in the Index view.</p>
<pre class="brush: xml; title: ; notranslate">
@{
    ViewBag.Title = &quot;Home Page&quot;;
}

&lt;h2&gt;@ViewBag.Message&lt;/h2&gt;

&lt;div id=&quot;ProfileContainer&quot;&gt;
    @{ Html.RenderAction(&quot;Profile&quot;); }
&lt;/div&gt;
</pre>
<p>Lastly, I have listed the scripts and css files that need to be linked below in the _Layout page for everything to work correctly.</p>
<pre class="brush: xml; title: ; wrap-lines: false; notranslate">
&lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot; /&gt;
    &lt;title&gt;@ViewBag.Title&lt;/title&gt;
    &lt;link href=&quot;@Url.Content(&quot;~/Content/Site.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;link href=&quot;@Url.Content(&quot;~/Content/themes/base/jquery.ui.all.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery-1.5.1.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/modernizr-1.7.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery-ui-1.8.11.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery.unobtrusive-ajax.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery.validate.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery.validate.unobtrusive.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;   
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/DialogForm.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;    
&lt;/head&gt;
</pre>
<p>The last script reference above is to a script I wrote called DialogForm.js.  This script (shown below) will make everything work.</p>
<pre class="brush: jscript; title: ; wrap-lines: false; notranslate">

$(function () {

    // Don't allow browser caching of forms
    $.ajaxSetup({ cache: false });

    // Wire up the click event of any current or future dialog links
    $('.dialogLink').live('click', function () {
        var element = $(this);

        // Retrieve values from the HTML5 data attributes of the link        
        var dialogTitle = element.attr('data-dialog-title');
        var updateTargetId = '#' + element.attr('data-update-target-id');
        var updateUrl = element.attr('data-update-url');

        // Generate a unique id for the dialog div
        var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
        var dialogDiv = &quot;&lt;div id='&quot; + dialogId + &quot;'&gt;&lt;/div&gt;&quot;;

        // Load the form into the dialog div
        $(dialogDiv).load(this.href, function () {
            $(this).dialog({
                modal: true,
                resizable: false,
                title: dialogTitle,
                buttons: {
                    &quot;Save&quot;: function () {
                        // Manually submit the form                        
                        var form = $('form', this);
                        $(form).submit();
                    },
                    &quot;Cancel&quot;: function () { $(this).dialog('close'); }
                }
            });

            // Enable client side validation
            $.validator.unobtrusive.parse(this);

            // Setup the ajax submit logic
            wireUpForm(this, updateTargetId, updateUrl);
        });
        return false;
    });
});

function wireUpForm(dialog, updateTargetId, updateUrl) {
    $('form', dialog).submit(function () {

        // Do not submit if the form
        // does not pass client side validation
        if (!$(this).valid())
            return false;

        // Client side validation passed, submit the form
        // using the jQuery.ajax form
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                // Check whether the post was successful
                if (result.success) {                    
                    // Close the dialog 
                    $(dialog).dialog('close');

                    // Reload the updated data in the target div
                    $(updateTargetId).load(updateUrl);
                } else {
                    // Reload the dialog to show model errors                    
                    $(dialog).html(result);

                    // Enable client side validation
                    $.validator.unobtrusive.parse(dialog);

                    // Setup the ajax submit logic
                    wireUpForm(dialog, updateTargetId, updateUrl);
                }
            }
        });
        return false;
    });
}
</pre>
<h3>Conclusion</h3>
<p>I know that was a lot to take in but after you do the setup once, all you need to do is make one call to Html.DialogFormLink and everything will be taken care of for you.  Hope this helps!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2011/08/11/asp-net-mvc-ajax-dialog-form-using-jquery-ui/feed/</wfw:commentRss>
			<slash:comments>71</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">880</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>

		<media:content url="https://nickstips.wordpress.com/wp-content/uploads/2011/08/dialog_form.png" medium="image">
			<media:title type="html">dialog_form</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC: Unauthenticated User Always Redirected to ~/Account/LogOn Despite Custom Sign In Url</title>
		<link>https://nickstips.wordpress.com/2011/07/27/asp-net-mvc-unauthenticated-user-always-redirected-to-accountlogon-despite-custom-sign-in-url/</link>
					<comments>https://nickstips.wordpress.com/2011/07/27/asp-net-mvc-unauthenticated-user-always-redirected-to-accountlogon-despite-custom-sign-in-url/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Thu, 28 Jul 2011 02:20:12 +0000</pubDate>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[404]]></category>
		<category><![CDATA[authentication]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=874</guid>

					<description><![CDATA[By default new ASP.NET MVC projects redirect any unauthenticated users who request resources that require authentication to the /Account/LogOn action. The log on page is defined in the web.config authentication section. It is my preference for users to &#8220;Sign in&#8221; instead of &#8220;Log on&#8221; so I changed the web.config to the following and changed the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>By default new ASP.NET MVC projects redirect any unauthenticated users who request resources that require authentication to the /Account/LogOn action.  The log on page is defined in the web.config authentication section.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication mode=&quot;Forms&quot;&gt;
  &lt;forms loginUrl=&quot;~/Account/LogOn&quot; timeout=&quot;2880&quot; /&gt;
&lt;/authentication&gt;
</pre>
<p>It is my preference for users to &#8220;Sign in&#8221; instead of &#8220;Log on&#8221; so I changed the web.config to the following and changed the action method name from LogOn to SignIn.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication mode=&quot;Forms&quot;&gt;
  &lt;forms loginUrl=&quot;~/Account/SignIn&quot; timeout=&quot;2880&quot; /&gt;
&lt;/authentication&gt;
</pre>
<p>After the change I tried accessing a page that required the user to be authorized with and unauthorized user and to my surprise, the site redirected me to /Account/LogOn and I got a 404 error saying the the resource could not be found.  It turns out this is a known issue with the ASP.NET MVC when the WebMatrix.Data.dll and WebMatrix.DataWeb.dll are added to the deployable assemblies collection.  This issue can be fixed by adding the following key to the appSettings section of the web.config.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;appSettings&gt;
  ...
  &lt;add key=&quot;loginUrl&quot; value=&quot;~/Account/SignIn&quot; /&gt;
&lt;/appSettings&gt;
</pre>
<p>I presume this will be fixed in the next release of ASP.NET MVC as a bug has been logged on Microsoft Connect <a href="https://connect.microsoft.com/webmatrix/feedback/details/665150/including-webmatrix-data-dll-webmatrix-webdata-dll-overrides-forms-loginurl">here</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2011/07/27/asp-net-mvc-unauthenticated-user-always-redirected-to-accountlogon-despite-custom-sign-in-url/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">874</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>
	</item>
		<item>
		<title>Unit Testing: Verify a Method Call Ignoring the Parameters</title>
		<link>https://nickstips.wordpress.com/2011/07/16/unit-testing-verify-a-method-call-ignoring-the-parameters/</link>
					<comments>https://nickstips.wordpress.com/2011/07/16/unit-testing-verify-a-method-call-ignoring-the-parameters/#comments</comments>
		
		<dc:creator><![CDATA[Nick Olsen]]></dc:creator>
		<pubDate>Sat, 16 Jul 2011 16:17:03 +0000</pubDate>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Moq]]></category>
		<guid isPermaLink="false">http://nickstips.wordpress.com/?p=868</guid>

					<description><![CDATA[I use Moq extensively when unit testing my applications. One of the nice features of Moq (and any other Mocking framework) is that you can verify which methods were called on a given interface during a test. By default, if you have a method on an interface that accepts parameters and you want to verify [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I use <a href="http://code.google.com/p/moq/">Moq</a> extensively when unit testing my applications.  One of the nice features of Moq (and any other Mocking framework) is that you can verify which methods were called on a given interface during a test.  By default, if you have a method on an interface that accepts parameters and you want to verify that it is called, you have to specify the exact parameters that should have been used in the method call for it to pass the test.  Example:</p>
<pre class="brush: csharp; title: ; notranslate">
public interface ICompanyService
{
    void Add(Company company);
}

[Test]
public void SignUp_Action_Calls_CompanyService_Add_Method()
{          
    // Arrange       
    var companyService = new Mock&lt;ICompanyService&gt;();     
    AccountController controller = new AccountController(companyService.Object);

    // Act
    var model = GetSignUpViewModel();
    var result = controller.SignUp(model);
    
    Company company = new Company();
    company.Name = model.Name;
    company.Address = model.Address;
    company.PhoneNumber = model.PhoneNumber;

    // Assert    
    companyService.Verify(x =&gt; x.Add(company));
}
</pre>
<p>If you need to test the actual data be passed to the Add method you can do this but if you just want to test whether or not the method was called regardless of the parameters supplied to the method, you can using Moq.  To do this, just use It.IsAny method supplied by the Moq framework to indicate that you just want to see if the method was called with any type of Company object.</p>
<pre class="brush: csharp; title: ; notranslate">
[Test]
public void SignUp_Action_Calls_CompanyService_Add_Method()
{          
    ...

    // Assert    
    companyService.Verify(x =&gt; x.Add(It.IsAny&lt;Company&gt;()));
}
</pre>
<p>Mocking frameworks are your friends and save hours of time if you know how to use them correctly.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://nickstips.wordpress.com/2011/07/16/unit-testing-verify-a-method-call-ignoring-the-parameters/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">868</post-id>
		<media:content url="https://2.gravatar.com/avatar/8fc6dcbff32e201233f935c56dd8e1d07f7cece583ef39cf367053d2e76b02ce?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Nick Olsen</media:title>
		</media:content>
	</item>
	</channel>
</rss>
