<?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>Patrick Desjardins&#039; Blog</title>
	<atom:link href="http://patrickdesjardins.com/blog/feed" rel="self" type="application/rss+xml" />
	<link>http://patrickdesjardins.com/blog</link>
	<description>Microsoft .Net Framework</description>
	<lastBuildDate>Sat, 19 May 2012 02:15:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>How to call anonymous function in Javascript?</title>
		<link>http://patrickdesjardins.com/blog/how-to-call-anonymous-function-in-javascript?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-call-anonymous-function-in-javascript</link>
		<comments>http://patrickdesjardins.com/blog/how-to-call-anonymous-function-in-javascript#comments</comments>
		<pubDate>Sat, 19 May 2012 02:15:51 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1097</guid>
		<description><![CDATA[You may have anonymous function that you want to call later in the same method (or to pass this one by parameter and call this one later). To be able to have a reference to this anonymous function, you need to use a variable that will keep a reference to this anonymous function. Later, when [...]]]></description>
			<content:encoded><![CDATA[<p>You may have anonymous function that you want to call later in the same method (or to pass this one by parameter and call this one later). To be able to have a reference to this anonymous function, you need to use a variable that will keep a reference to this anonymous function. Later, when you want to use it, you simply need to call it by writing the variable name with parentheses.</p>
<pre class="brush: jscript; title: ; notranslate">
var anonymous= function(){
    alert(&quot;Test123&quot;);
};
anonymous();
</pre>
<p>Pretty simple, isn&#8217;t?</p>
<p>From here you can have more complex prototype (Javascript class mechanism).</p>
<pre class="brush: jscript; title: ; notranslate">
function MyClass(val1, val2){
    this.val1 = val1;
    this.val2 = val2;
    this.function1 = function()
    {
        alert(this.val1);
    }
}
//...
var x = new MyClass('Test','Hello');
x.function1();
</pre>
<p>This example show you that you can have an anonymous function that can be called later like the previous example.</p>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/how-to-call-anonymous-function-in-javascript/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using onclick for Javascript function instead of href</title>
		<link>http://patrickdesjardins.com/blog/using-onclick-for-javascript-function-instead-of-href?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-onclick-for-javascript-function-instead-of-href</link>
		<comments>http://patrickdesjardins.com/blog/using-onclick-for-javascript-function-instead-of-href#comments</comments>
		<pubDate>Thu, 17 May 2012 00:37:41 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1087</guid>
		<description><![CDATA[Many people will use Javascript function call directly into the href attribute of the link tag when they want to execute Javascript. This let them execute Javascript without having to have the fallback of having the browser scrolling to the top. The problem with this method, other than having client script into an attribute which [...]]]></description>
			<content:encoded><![CDATA[<p>Many people will use Javascript function call directly into the href attribute of the link tag when they want to execute Javascript. This let them execute Javascript without having to have the fallback of having the browser scrolling to the top. The problem with this method, other than having client script into an attribute which is been created for anchor link and external link is that it displays the Javascript code in the status bar of the browser.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;a href='javascript:MyFunction(1,2,3)'&gt;Click me&lt;/a&gt;
</pre>
<p>To avoid this kind of behavior, which is not very clean, is to simply use the onclick attribut which is dedicated to receive Javascript&#8217;s call.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;a href='#' onclick=&quot;MyFunction(1,2,3);return false;&quot;&gt;Click me&lt;/a&gt;
</pre>
<p>As you can see, the onclick contain also a second Javascript&#8217;s statement which indicate the to the browser to not execute the link in the href attribute (the hash tag). This will prevent the browser to scroll up. In fact, you could specify a page to go if something goes wrong with the Javascript or if the user doesn&#8217;t have Javascript enable.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;a href='fallbackpage.html' onclick=&quot;MyFunction(1,2,3);return false;&quot;&gt;Click me&lt;/a&gt;
</pre>
<p>In that case, if Javascript is disable, the user will be redirected to the &#8220;fallbackpage.html&#8221;.</p>
<p>You can also not systematic use the `return false` and simply use directly the return of your function.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;a href='nextpage.aspx' onclick=&quot;return MyFunction(1,2,3);&quot;&gt;Click me&lt;/a&gt;
</pre>
<p>In that case, this will call the MyFunction fonction and if the result is false will do nothing with the navigation and if true will move the user to &#8220;nextpage.aspx&#8221;. This can be interesting in a scenario where you need to have to confirm something with the user or if you need to validate data before moving to the next step.</p>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/using-onclick-for-javascript-function-instead-of-href/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is the HandleError attribute goal?</title>
		<link>http://patrickdesjardins.com/blog/what-is-the-handleerror-attribute-goal?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=what-is-the-handleerror-attribute-goal</link>
		<comments>http://patrickdesjardins.com/blog/what-is-the-handleerror-attribute-goal#comments</comments>
		<pubDate>Thu, 10 May 2012 00:34:26 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[ASP.MVC]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1069</guid>
		<description><![CDATA[In Asp.Net Mvc, you can add an attribute to your controller or to some actions of your controller to tell Asp that you will take care of errors if they occur. You simply need to add the attribute HandleError. You can take care of specific error by specifying one or many type of exception that [...]]]></description>
			<content:encoded><![CDATA[<p>In Asp.Net Mvc, you can add an attribute to your controller or to some actions of your controller to tell Asp that you will take care of errors if they occur. You simply need to add the attribute HandleError.</p>
<pre class="brush: csharp; title: ; notranslate">
[HandleError]
public class MyController : Controller
{
}
</pre>
<p>You can take care of specific error by specifying one or many type of exception that you want to handle. To do, simply add the property ExceptionType at your HandleError level.</p>
<pre class="brush: csharp; title: ; notranslate">
[HandleError(ExceptionType = typeof(SqlException))]
public class MyController : Controller
{
}
</pre>
<p>If you need to handle multiple exception, you will need to use multiple attributes.</p>
<pre class="brush: csharp; title: ; notranslate">
[HandleError(ExceptionType = typeof(SqlException))]
[HandleError(ExceptionType = typeof(NullReferenceException))]
public class MyController : Controller
{
}
</pre>
<p>You can also in HandleError attribute specify what view to display.</p>
<pre class="brush: csharp; title: ; notranslate">
[HandleError(ExceptionType = typeof(SqlException), View=&quot;SqlView&quot;)]
public class MyController : Controller
{
}
</pre>
<p>If you do not specify any view, the exception will be viewed in the default error page. At first, it will check for Error.aspx in the Views folder associated with the Controller and then go see in the Shared folder.</p>
<p>Now you have the control to display specific exception to a specific view, others errors to the generic error page or to do not use anything and use the default ASP error page (yellow page of death) by setting the customErrors to off in the web.config file.<a href="http://patrickdesjardins.com/blog/what-is-the-handleerror-attribute-goal/defaultasperrorpage" rel="attachment wp-att-1070"><img src="http://patrickdesjardins.com/blog/wp-content/uploads/2012/05/defaultAspErrorPage-400x239.png" alt="" title="defaultAspErrorPage" width="400" height="239" class="aligncenter size-medium wp-image-1070" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/what-is-the-handleerror-attribute-goal/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get from an ASP.MVC Controller the absolute path for an action?</title>
		<link>http://patrickdesjardins.com/blog/how-to-get-from-a-asp-mvc-controller-the-absolute-path-for-an-action?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-get-from-a-asp-mvc-controller-the-absolute-path-for-an-action</link>
		<comments>http://patrickdesjardins.com/blog/how-to-get-from-a-asp-mvc-controller-the-absolute-path-for-an-action#comments</comments>
		<pubDate>Fri, 04 May 2012 18:33:40 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[ASP.MVC]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1063</guid>
		<description><![CDATA[You may need to have the full url of an action in the case you desire to do some Javascript redirection. You may want to pass which url to redirect via Json. Using not a fully constructed url will fail the redirection. The trick is to pass a full url. Asp.Net MVC give you the [...]]]></description>
			<content:encoded><![CDATA[<p>You may need to have the full url of an action in the case you desire to do some Javascript redirection. You may want to pass which url to redirect via Json. Using not a fully constructed url will fail the redirection. The trick is to pass a full url. Asp.Net MVC give you the possibility to generate a fully formed url with the URL helper. The class that will help you to get the url is called &#8220;<strong>UrlHelper</strong>&#8220;.</p>
<p>The class contains many <strong>Action</strong> method that are overloaded with many parameters. The one that interest us has 4 parameters.</p>
<pre class="brush: csharp; title: ; notranslate">
public string Action(string actionName, string controllerName, object routeValues, string protocol)
{
//...
}
</pre>
<p>The first parameter is the action name to which you want to have the url. The second one is the controller name. This one can be NULL if you use it inside a controller and want to have the url with the same url. If you are inside the action X or the controller Y and you put NULL, you will get a url for the controller Y. The route values doesn&#8217;t interest us in this case. You can pass NULL. The last parameter is the protocol. When you provide a procotol, the url returned by the Action method will contain a full absolute url. A trick is to use <strong>Request.Url.Scheme</strong> which will use the current protocol used by the method that has been called by the controller. That mean that if you are using HTTP that the url formed will have the same protocol, HTTP. Samething if the request would have been done by a HTTPS request, the formed url would contain HTTPS.</p>
<p>We can take a look inside Asp.Net MVC source code and see that the Action method with 4 parameters call GenerateURL with a lot of parameters.</p>
<pre class="brush: csharp; title: ; notranslate">
        public string Action(string actionName, string controllerName, object routeValues, string protocol) {
            return GenerateUrl(null /* routeName */, actionName, controllerName, protocol, null /* hostName */, null /* fragment */, new RouteValueDictionary(routeValues), RouteCollection, RequestContext, true /* includeImplicitMvcValues */);
        }
</pre>
<p>The GenerateUrl method check the protocol and if not NULL will build the absolute URL.</p>
<pre class="brush: csharp; highlight: [9]; title: ; notranslate">
public static string GenerateUrl(string routeName, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, bool includeImplicitMvcValues) {
            string url = GenerateUrl(routeName, actionName, controllerName, routeValues, routeCollection, requestContext, includeImplicitMvcValues);

            if (url != null) {
                if (!String.IsNullOrEmpty(fragment)) {
                    url = url + &quot;#&quot; + fragment;
                } 

                if (!String.IsNullOrEmpty(protocol) || !String.IsNullOrEmpty(hostName)) {
                    Uri requestUrl = requestContext.HttpContext.Request.Url;
                    protocol = (!String.IsNullOrEmpty(protocol)) ? protocol : Uri.UriSchemeHttp;
                    hostName = (!String.IsNullOrEmpty(hostName)) ? hostName : requestUrl.Host;

                    string port = String.Empty;
                    string requestProtocol = requestUrl.Scheme;

                    if (String.Equals(protocol, requestProtocol, StringComparison.OrdinalIgnoreCase)) {
                        port = requestUrl.IsDefaultPort ? String.Empty : (&quot;:&quot; + Convert.ToString(requestUrl.Port, CultureInfo.InvariantCulture));
                    } 

                    url = protocol + Uri.SchemeDelimiter + hostName + port + url;
                }
            } 

            return url;
        }
</pre>
<p>So, that mean that if you want to have your action method to get an absolute URL you would need to call:</p>
<pre class="brush: csharp; title: ; notranslate">
return Json(new JsonResponse { url = Url.Action(&quot;MyActionOfThisController&quot;, null, null, Request.Url.Scheme)});
</pre>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/how-to-get-from-a-asp-mvc-controller-the-absolute-path-for-an-action/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Telerik MVC grid can insert new rows at the bottom of the grid since 2012 sp1</title>
		<link>http://patrickdesjardins.com/blog/telerik-mvc-grid-can-insert-new-rows-at-the-bottom-of-the-grid-since-2012-sp1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=telerik-mvc-grid-can-insert-new-rows-at-the-bottom-of-the-grid-since-2012-sp1</link>
		<comments>http://patrickdesjardins.com/blog/telerik-mvc-grid-can-insert-new-rows-at-the-bottom-of-the-grid-since-2012-sp1#comments</comments>
		<pubDate>Wed, 02 May 2012 02:26:46 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[Telerik Asp.Net MVC]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1054</guid>
		<description><![CDATA[It&#8217;s rare that I am writing about third party control but Telerik grid has a new feature that is kinda hard to find any way to implement. If you want to insert a new row to a Telerik ASP.Net MVC grid that you need to add a call to the method InsertRowPosition. This can be [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s rare that I am writing about third party control but Telerik grid has a new feature that is kinda hard to find any way to implement. If you want to insert a new row to a Telerik ASP.Net MVC grid that you need to add a call to the method <strong>InsertRowPosition</strong>. This can be done inside the method <strong>Editable </strong>of the grid.</p>
<pre class="brush: csharp; title: ; notranslate">
  @Html.Telerik().Grid&lt;YourObjectType&gt;().Editable(e=&gt;e.InsertRowPosition(GridInsertRowPosition.Bottom))
</pre>
<p>This is a short snippet of code to demonstrate how to add a row at the bottom of a grid with Telerik Grid.</p>
<p>Of course, to the button to add a new row you need to use the ToolBar method to add a command to insert. This is done by adding <strong>ToolBar </strong>method to the Telerik().Grid().</p>
<pre class="brush: csharp; title: ; notranslate">
.ToolBar(c=&gt; c.Insert().ButtonType(GridButtonType.Text))
</pre>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/telerik-mvc-grid-can-insert-new-rows-at-the-bottom-of-the-grid-since-2012-sp1/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to localize property name?</title>
		<link>http://patrickdesjardins.com/blog/how-to-localize-property-name?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-localize-property-name</link>
		<comments>http://patrickdesjardins.com/blog/how-to-localize-property-name#comments</comments>
		<pubDate>Mon, 30 Apr 2012 23:07:02 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[ASP.MVC]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1046</guid>
		<description><![CDATA[If you are using Html Helper to generate your form you may end up with label with the property name into it. You may also have error message with the property name. The problem is if your object contain English term, you would prefer not to show them in English if you write something in [...]]]></description>
			<content:encoded><![CDATA[<p>If you are using Html Helper to generate your form you may end up with label with the property name into it. You may also have error message with the property name. The problem is if your object contain English term, you would prefer not to show them in English if you write something in French.</p>
<pre class="brush: csharp; title: ; notranslate">
public class Person
{
    public string Name { get; set; }
}
</pre>
<p>The example above could display the word &#8220;Name&#8221; in a localized string, which is not what we want. But, if we use the <strong>Display </strong>data annotation attribute, it&#8217;s possible to localize the property Name.</p>
<pre class="brush: csharp; title: ; notranslate">
public class Person
{
    [Display(ResourceType = typeof(ResourceFileTypeHere), Name=&quot;NamePropertyKey&quot;)]
    public string Name { get; set; }
}
</pre>
<p>This will search inside the resource specified the key inside the Name attribute. That&#8217;s it, you have your property localized.</p>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/how-to-localize-property-name/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to localize data attribute in MVC3?</title>
		<link>http://patrickdesjardins.com/blog/how-to-localize-data-attribute-in-mvc3?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-localize-data-attribute-in-mvc3</link>
		<comments>http://patrickdesjardins.com/blog/how-to-localize-data-attribute-in-mvc3#comments</comments>
		<pubDate>Sun, 29 Apr 2012 19:00:10 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[ASP.MVC]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1042</guid>
		<description><![CDATA[If you are using the Data Annotation with Asp.Net MVC you might need to localize the message from these annotation. Here is an example: If you want to have the Data Annotation translated in many languages, you should use two others properties that are : ErrorMessageResourceType and ErrorMessageResourceName. This will let you specify the resource [...]]]></description>
			<content:encoded><![CDATA[<p>If you are using the Data Annotation with Asp.Net MVC you might need to localize the message from these annotation.</p>
<p>Here is an example:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Person
{
    [Required(ErrorMessage=&quot;FirstName is required&quot;)]
    public string FirstName { get; set; }
    //...
}
</pre>
<p>If you want to have the Data Annotation translated in many languages, you should use two others properties that are : <strong>ErrorMessageResourceType</strong> and <strong>ErrorMessageResourceName</strong>. This will let you specify the resource type and the resouce name which is the key of inside the resource file.</p>
<pre class="brush: csharp; title: ; notranslate">
public class Person
{
    [Required(ErrorMessageResourceType=typeof(MyResourcesNameSpace.ResourcesFile), ErrorMessageResourceName=&quot;FirstNameRequiredKey&quot;)]
    public string FirstName { get; set; }
    //...
}
</pre>
<p>This way, you will have your application localized from the Model to the View without any problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/how-to-localize-data-attribute-in-mvc3/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Html Extension Helper with generic access to object property</title>
		<link>http://patrickdesjardins.com/blog/html-extension-helper-with-generic-access-to-object-property?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=html-extension-helper-with-generic-access-to-object-property</link>
		<comments>http://patrickdesjardins.com/blog/html-extension-helper-with-generic-access-to-object-property#comments</comments>
		<pubDate>Wed, 25 Apr 2012 01:16:06 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[ASP.MVC]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1036</guid>
		<description><![CDATA[It&#8217;s possible to create a custom generic Html Extension Helper with the use of Expression Helper and if required the ModelMetadata to get the value. The variable fullPropertyNamex.MyClassProperty1) With little or no code you can setup Html Helper that is strongly typed. This has the advantage to not write string. This of course is better [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s possible to create a custom generic <strong>Html Extension Helper</strong> with the use of Expression Helper and if required the ModelMetadata to get the value.</p>
<pre class="brush: csharp; title: ; notranslate">
    public static string MyExtensionFor&lt;TModel, TProperty&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; property)
	{
		var meta = ModelMetadata.FromLambdaExpression(property, this.HtmlHelper.ViewData);
		string fullPropertyName = HtmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(property));

		//Do what you need to do
	}
</pre>
<p>	The variable <strong>fullPropertyName</strong contain the property name and the <strong>meta</strong> data contain the value of the property if required.</p>
<p>	@Html.MyExtensionFor(x=>x.MyClassProperty1)</p>
<p>With little or no code you can setup Html Helper that is strongly typed. This has the advantage to not write string. This of course is better to reduce the change to write a wrong string but also help the refactoring because all refactoring tools works with property name change.</p>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/html-extension-helper-with-generic-access-to-object-property/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to save the ModelState into session following the good practice</title>
		<link>http://patrickdesjardins.com/blog/how-to-save-the-modelstate-into-session-following-the-good-practice?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-save-the-modelstate-into-session-following-the-good-practice</link>
		<comments>http://patrickdesjardins.com/blog/how-to-save-the-modelstate-into-session-following-the-good-practice#comments</comments>
		<pubDate>Sat, 21 Apr 2012 02:20:29 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[ASP.MVC]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1032</guid>
		<description><![CDATA[Tim Barcz, Matt Hawley, Stephen Walther and Scott Guthrie (VP at Microsoft and lead for many project like Entity Framework, Asp.Net, etc) have already discussed about this problematic and created the PRG pattern to solve this problem. In fact, to solve this problem you should not handle manually the ModelState but simply use Import and [...]]]></description>
			<content:encoded><![CDATA[<p>Tim Barcz, Matt Hawley, Stephen Walther and Scott Guthrie (VP at Microsoft and lead for many project like Entity Framework, Asp.Net, etc) have already discussed about this problematic and created the PRG pattern to solve this problem. In fact, to solve this problem you should not handle manually the ModelState but simply use Import and Export attribute like the following example.</p>
<pre class="brush: csharp; title: ; notranslate">
[AcceptVerbs(HttpVerbs.Get), ImportModelStateFromTempData]
public ActionResult MyAction(ModelObject myObject)
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post), ExportModelStateToTempData]
public ActionResult MyActionSubmit(ModelObject  myObject)
{
   return View();
}
</pre>
<p>These attributes are not from the .Net framework and you need to have them inside your project by creating them. Once it&#8217;s done once, it&#8217;s done for the life time of your project.</p>
<p>First, you need to create the attributes. To do, you need to create a class that inherit the class <strong>ActionFilterAttribute</strong>. Since we are using 2 attributes that share the same information, we will create 3 classes. The first one will contain the sharing key for the session and the two others will be for the Import and Export.</p>
<pre class="brush: csharp; title: ; notranslate">
public abstract class ModelStateTempDataTransfer : ActionFilterAttribute
{
    protected static readonly string Key = typeof(ModelStateTempDataTransfer).FullName;
}
</pre>
<p>Then, the class to export. Here you can add more custom code for your project. This version will all the ModelState only if this one contain errors.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ExportModelStateToTempData : ModelStateTempDataTransfer
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //Only export when ModelState is not valid
        if (!filterContext.Controller.ViewData.ModelState.IsValid)
        {
            //Export if we are redirecting
            if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
            {
                filterContext.Controller.TempData[Key] = filterContext.Controller.ViewData.ModelState;
            }
        }

        base.OnActionExecuted(filterContext);
    }
}
</pre>
<p>The last class will import the ModelState. In fact, it will merge the new one with the old one in the session.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ImportModelStateFromTempData : ModelStateTempDataTransfer
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;

        if (modelState != null)
        {
            //Only Import if we are viewing
            if (filterContext.Result is ViewResult)
            {
                filterContext.Controller.ViewData.ModelState.Merge(modelState);
            }
            else
            {
                //Otherwise remove it.
                filterContext.Controller.TempData.Remove(Key);
            }
        }

        base.OnActionExecuted(filterContext);
    }
}
</pre>
<p>As you can see, we do not use the session directly but we store everything into the TempData which use the session but handle the life cycle for us. This mean that it won&#8217;t stay for 20 minutes (default value of a session life time). It will stay until the next post back and be there if the request is redirected.</p>
<p>You can see it in the MVC open source project called <a href="http://mvccontrib.codeplex.com/">MVCContrib </a>(slightly modified version of this one). You can also find the source of the code in this blog post at this <a href="http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg">website</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/how-to-save-the-modelstate-into-session-following-the-good-practice/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework 4.3 delete cascade with code first (Poco)</title>
		<link>http://patrickdesjardins.com/blog/entity-framework-4-3-delete-cascade-with-code-first-poco?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=entity-framework-4-3-delete-cascade-with-code-first-poco</link>
		<comments>http://patrickdesjardins.com/blog/entity-framework-4-3-delete-cascade-with-code-first-poco#comments</comments>
		<pubDate>Thu, 19 Apr 2012 22:54:55 +0000</pubDate>
		<dc:creator>Patrick Desjardins</dc:creator>
				<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://patrickdesjardins.com/blog/?p=1023</guid>
		<description><![CDATA[If you have a parent->child relationship between two of your classes and you delete the parent, you may want to delete all children. To do, you need to have a &#8220;DELETE CASCADE&#8221; statement on your foreign key. Here is a simple example: The problem is that if you are using Entity Framework 4.3 and try [...]]]></description>
			<content:encoded><![CDATA[<p>If you have a parent->child relationship between two of your classes and you delete the parent, you may want to delete all children. To do, you need to have a &#8220;DELETE CASCADE&#8221; statement on your foreign key. Here is a simple example:</p>
<pre class="brush: sql; title: ; notranslate">
CREATE TABLE [Tax](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Description] [nvarchar](100) NULL,
CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED
GO

CREATE TABLE [ParentDetail](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Parent_ID] [int] NOT NULL,
CONSTRAINT [PK_ParentDetail] PRIMARY KEY CLUSTERED
GO

ALTER TABLE [ParentDetail]  WITH CHECK ADD  CONSTRAINT [FK_ParentDetail_Parent] FOREIGN KEY([Parent_ID])
REFERENCES [Parent] ([ID])
ON DELETE CASCADE
GO
</pre>
<p>The problem is that if you are using Entity Framework 4.3 and try to delete a Parent entity, you will end having this error :</p>
<blockquote><p>An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.</p></blockquote>
<p>The inner exception message will contain something similar to this:</p>
<blockquote><p>Cannot insert the value NULL into column &#8216;Parent_ID&#8217;, table &#8216;NutCache.Schema_NutCache.ParentDetail&#8217;; column does not allow nulls. UPDATE fails. The statement has been terminated.</p></blockquote>
<p>So, what does it means? It try to delete the Parent and to set into each ParentDetail the ID NULL because it&#8217;s been erased. This is not what we want. In fact, we would like to have all ParentDetail to me removed as well. This is a little bit the reason why we have specify on the SQL to have a cascade.</p>
<p>You can do it manually in your project:</p>
<pre class="brush: csharp; title: ; notranslate">
var listDetail = parent.ParentDetails.ToList();
foreach (var ParentDetail in listDetail){
	Database.ParentDetails.Remove(ParentDetail);
}

Database.Parents.Remove(Parent);
Database.SaveChanges();
</pre>
<p>This will produce multiple amount of SQL statement on the SQL Server. One for each details and 1 for the Parent itself.</p>
<p>But, if you go to your database context and you specify in the <strong>OnModelCreating</strong> a rule about the cascade it will work as it&#8217;s suppose to do.</p>
<pre class="brush: csharp; title: ; notranslate">
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//...
modelBuilder.Entity&lt;Parent&gt;().HasMany(e =&gt; e.ParentDetails).WithOptional(s =&gt; s.Parent).WillCascadeOnDelete(true);
//...
</pre>
<p>That&#8217;s it! Now you can simply delete the Parent without having to delete manually every children.</p>
<pre class="brush: csharp; title: ; notranslate">
Database.Parents.Remove(Parent);
Database.SaveChanges();
</pre>
<p>On the SQL server side, you can see the database to have the same amount of delete statement executed. So, you do not save on the amount of query but save on the amount of logic to handle on the C# side because you do not have to care to delete every details.</p>
<p>On a special note, you do not need to have the table having a reference with the On Delete Cascade. You can handle the cascade only on the Entity DbContext with OnModelCreating. If you specify it on the Sql Server Database side, this only will enforce the integrity on the database side but won&#8217;t be automatically applied on the delete with EF.</p>
]]></content:encoded>
			<wfw:commentRss>http://patrickdesjardins.com/blog/entity-framework-4-3-delete-cascade-with-code-first-poco/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

