﻿<?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>Programming By A Tool &#187; MVC</title>
	<atom:link href="http://byatool.com/tag/mvc/feed/" rel="self" type="application/rss+xml" />
	<link>http://byatool.com</link>
	<description>This is my recorded stumbling through ASP.Net, Framework 3.5, C# 3.0, Ajax, Javascript, and Love.  Stay, learn, destroy.  It's your life.</description>
	<lastBuildDate>Thu, 03 May 2012 17:28:21 +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>Nemerle MVC 3 project</title>
		<link>http://byatool.com/nemerle/nemerle-mvc-3-project/</link>
		<comments>http://byatool.com/nemerle/nemerle-mvc-3-project/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 15:57:35 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Nemerle]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=2522</guid>
		<description><![CDATA[You can get it from my new git hub disaster. Just out of curiosity I was trying to see if I could get a basic MVC 3 project going with Nemerle. Never heard of Nemerle? Yeah neither had I up until last week. It&#8217;s a pretty powerful .Net language that can be used to expand [...]]]></description>
			<content:encoded><![CDATA[<p>You can get it from <a href="https://github.com/byatool/BaseNemerleMvc">my new git hub disaster.</a></p>
<p>Just out of curiosity I was trying to see if I could get a basic MVC 3 project going with <a href="http://nemerle.org/About/">Nemerle</a>. Never heard of <a href="http://nemerle.org/About/">Nemerle</a>? Yeah neither had I up until last week. It&#8217;s a pretty powerful .Net language that can be used to expand the default functionality of .Net. It&#8217;s worth checking out.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/nemerle/nemerle-mvc-3-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC 2/C# 4â€¦ Dynamic Model and Should You Use It?</title>
		<link>http://byatool.com/pontification/asp-net-mvc-2c-4-dynamic-model-and-should-you-use-it/</link>
		<comments>http://byatool.com/pontification/asp-net-mvc-2c-4-dynamic-model-and-should-you-use-it/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 00:11:53 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ExpandoObject]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1826</guid>
		<description><![CDATA[So there&#8217;s a new sheriff in town and its name is dynamic. Actually, its not really that new and that&#8217;s a horribly misused cliche. My lack of literary genius aside, I&#8217;ve been looking for a reason to use dynamic. Then it came to me: Models. Now the only reason why I started down that path [...]]]></description>
			<content:encoded><![CDATA[<p>So there&#8217;s a new sheriff in town and its name is dynamic.  Actually, its not really that new and that&#8217;s a horribly misused cliche.  My lack of literary genius aside, I&#8217;ve been looking for a reason to use dynamic.  Then it came to me:  Models.  Now the only reason why I started down that path was the use of Python where pretty much anything is dynamic.  In using python, I got used to not embracing the rigidity of classes for models and adopted a more &#8220;Oh what the f&#8211;k&#8221; attitude.  Back in the .net world though, I was using typed views.  Then I readopted the &#8220;Oh what the f&#8211;k&#8221; attitude and applied it to .net mvc.</p>
<p>Here&#8217;s an example:</p>
<pre>    [<span style="color: #008080;">RequiresAuthentication</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> ShowBasicInfo()
    {
      <span style="color: #008080;">IState</span> currentState = ObjectFactory.Create();
      <span style="color: #0000ff;">dynamic</span> returnModel = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ExpandoObject</span>();

      returnModel.UserName = currentState.CurrentUser.UserName;

      <span style="color: #0000ff;">return</span> View(AccountActions.ShowBasicInfo, returnModel);
    }
</pre>
<p>As you can see, I created a dynamic class and just added a property to it.  Now on the view side:</p>
<pre>...
<span style="color: #ff6600;">@model</span> dynamic
...
          &lt;<span style="color: #800000;">label</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"showBasicInfoEmail"</span> <span style="color: #0000ff;">name=</span><span style="color: #ff0000;">"showBasicInfoEmail"</span>&gt;<span style="color: #ff6600;">@Model.UserName</span>&lt;/<span style="color: #800000;">label</span>&gt;
...
</pre>
<p>So if that&#8217;s all you&#8217;re here for, well there you go.   Now get out.</p>
<p>Ok so the real point to this post was actually the &#8220;should I?&#8221; Now with .Net, you really have to adopt a &#8220;should I?&#8221; attitude on anything that is new otherwise it might come back to bite you in the a&#8211;.  (Update panels anyone?)  Just using something because it looks easier is NOT a reason to do so.</p>
<p>The reason why I originally gravitated toward typed views was I didn&#8217;t like all the magic sting junk that came with the View dictionary, or whatever the hell it was called.  (I&#8217;m too lazy to look it up) Typed views gave a sort of concrete nature much like an interface does to a class.  You knew exactly WHAT the view could show based on the model.  This is good I still think in an environment where you don&#8217;t trust people to code correctly or when a person needs an easy place to look up what the incoming model contains.  After all, on the second point I mean, its a lot easier to look at a class to find EXACTLY what the model has than looking at a controller action code.  Simple for reference.</p>
<p>With that being said, getting stuck in model hell can happen. After all for every action there is an equal and&#8230; wait&#8230; there is a model.  Yeah you can reuse models to cut that down, but its not too hard to imagine it becoming a model infested nightmare.  Sometimes you just have to take the good and the bad, but sometimes you&#8217;re able to trust people and just go with what is easier.</p>
<p>Why trust? With Python and it overall dynamic nature, it was easy to see that such a tool put in the wrong hands could be a disaster.  Anyone who has worked with JavaScript will know this pain.  Python is just a fancy way to annihilate your foot, so the concept of allowing dynamic models only made me shiver like a prostitute on Christmas.  Sorry, that wasn&#8217;t appropriate.  I meant a prostitute on a non religious holiday like Thanksgiving or the Chinese New Year. (Sorry non Christian readers)</p>
<p>On the other hand, when in a small group where you have less time and more to do, it could be used as a compromise as it doesn&#8217;t use the hated magic string dictionary thing approach, but still had a class like feel.  And on top of that, if you wish to create models later, it would be extremely easy to swap the @model dynamic with whatever class type you need.  So in that way, I can almost stop my non stop convulsing that is a natural reaction to doing something I deem bad.</p>
<p>Answer is:  I don&#8217;t f&#8211;king know right now, but I&#8217;m going to fly with it and see how I like it.</p>
<p>Side note: One drawback of the dynamic route is the lack of intellisense.  That could be a deal killer for some.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/asp-net-mvc-2c-4-dynamic-model-and-should-you-use-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery: Find a Form Action Using Jquery</title>
		<link>http://byatool.com/ui/jquery-find-a-form-action-using-jquery/</link>
		<comments>http://byatool.com/ui/jquery-find-a-form-action-using-jquery/#comments</comments>
		<pubDate>Sun, 26 Sep 2010 16:59:04 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[UI]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1699</guid>
		<description><![CDATA[This is pretty useful for people trying to pass in a generated action to a javascript file.Â  Eh? SKIP IF YOU DON&#8217;T CARE ABOUT A REASON FOR USING THIS: Say you are using the jQuery post method to send things back to the server but all the code for that is in a seperate javascript [...]]]></description>
			<content:encoded><![CDATA[<p>This is pretty useful for people trying to pass in a generated action to a javascript file.Â  Eh?</p>
<h1><span style="color: #ff0000;">SKIP IF YOU DON&#8217;T CARE ABOUT A REASON FOR USING THIS:</span></h1>
<p>Say you are using the jQuery post method to send things back to the server but all the code for that is in a seperate javascript file.Â  Well you can&#8217;t really do this:</p>
<pre>jQuery.ajax({
      type:<span style="color: #800000;">'POST'</span>,
      url: <span style="color: #ff9900;">&lt;%=</span> someMethodForCreatingAUrl(<span style="color: #ff0000;">'controller'</span>, <span style="color: #ff0000;">'action'</span>) <span style="color: #ff9900;">%&gt;</span>,
      dataType:'json',
      data:{
        email: user.userName,
        password: user.password
      },
      success: function(result){
        onSuccess(result);
      },
      error:function (xhr, ajaxOptions, thrownError){
        alert(xhr.status);
      }
    });</pre>
<p>if that is in the javascript file.</p>
<p>What you can do is this on the html file:</p>
<pre>  &lt;<span style="color: #800000;">form</span> <span style="color: #0000ff;">id=</span><span style="color: #ff0000;">"formCreateUser"</span> <span style="color: #0000ff;">name=</span><span style="color: #ff0000;">"formCreateUser"</span> <span style="color: #0000ff;">method=</span><span style="color: #ff0000;">"post"</span> <span style="color: #0000ff;">action=</span>"${someMethodForCreatingAUrl('controller', 'action')}"&gt;</pre>
<p>And in the javascript file:</p>
<h1><span style="color: #ff0000;">ANSWER:</span></h1>
<pre>  <span style="color: #0000ff;">var</span> formAction = jQuery(ELEMENT_LOGIN_FORM).attr(<span style="color: #ff0000;">'action'</span>);</pre>
<p>And there you go. You have the action.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/ui/jquery-find-a-form-action-using-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spark View Engine, ASP.Net MVC, and You</title>
		<link>http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/</link>
		<comments>http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/#comments</comments>
		<pubDate>Thu, 27 May 2010 15:10:28 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Spark]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1395</guid>
		<description><![CDATA[So one of the things I was forced to use, semi kicking and screaming, at one point in my illustrious career was the Spark View Engine for ASP.Net MVC. Actually that&#8217;s not totally true. I only kicked for a bit then skipped the screaming once I noticed what it did: It took all the ugly [...]]]></description>
			<content:encoded><![CDATA[<p>So one of the things I was forced to use, semi kicking and screaming, at one point in my illustrious career was the <a href="http://dev.dejardin.org/">Spark View Engine for ASP.Net MVC</a>.  Actually that&#8217;s not totally true.  I only kicked for a bit then skipped the screaming once I noticed what it did:  It took all the ugly &lt;% %&gt; junk out of the html&#8230; <a href="http://byatool.com/pontification/just-use-html-why-mvc-can-be-a-good-thing/">my beautiful html</a>&#8230; and made things like for loops much nicer.  Mind you, this is mererly the tip of the ice pick&#8230; eh berg I meant berg&#8230; there&#8217;s a lot more to it.  It handles things like Master Pages and Partial Controls pretty darn well as well as caching javascript files on the go.  Sounds good?  Well it should and if it doesn&#8217;t, I don&#8217;t think we can be friends.</p>
<p>First off, I just wanted to quickly write something up on how to get it all going and because I&#8217;m such a nice guy <a href="http://byatool.com/Hosted/PhotoShare.UI.zip">I even have a project that is ready to go</a> for common use.  The catch is that I made it in 2010 so if you don&#8217;t have that yet, you could be screwed.  Then again I could type out a lot of the steps too.  You just don&#8217;t know.</p>
<p>First off you can either get the assemblies from my hosted project, <a href="http://sparkviewengine.codeplex.com/releases/view/27601">or you can go here</a> and get it.  Either way, I don&#8217;t care.  No really, I don&#8217;t.  Not just sayin&#8217;.  The care cup had run dry.</p>
<p>The two assemblies you need to reference in your project are:</p>
<pre>  spark.dll
  spark.mvc
</pre>
<p>Next add this line to the Application_Start method in the Global.asax.cs file:</p>
<pre>  <span style="color: #008080;">ViewEngines</span>.Engines.Add(<span style="color: #0000ff;">new</span> <span style="color: #008080;">SparkViewFactory</span>());
</pre>
<p>After that, you&#8217;ll have to add a little somethin&#8217; somethin&#8217; to your web.config.  I know, I know.  This is all so very hard.  Live strong like Lance.</p>
<pre>  &lt;<span style="color: #ff0000;">configuration</span>&gt;
    ...
    &lt;<span style="color: #ff0000;">configSections</span>&gt;
      &lt;<span style="color: #ff0000;">section</span> <span style="color: #0000ff;">name=</span><span style="color: #800000;">"spark"</span> <span style="color: #ff0000;">type=</span><span style="color: #800000;">"Spark.Configuration.SparkSectionHandler, Spark"</span>/&gt;
    &lt;/<span style="color: #ff0000;">configSections</span>&gt;
    ...
    &lt;<span style="color: #ff0000;">spark</span>&gt;
      &lt;<span style="color: #ff0000;">compilation</span> <span style="color: #0000ff;">debug=</span><span style="color: #800000;">"true"</span> <span style="color: #0000ff;">defaultLanguage=</span><span style="color: #800000;">"CSharp"</span>&gt;
        &lt;<span style="color: #ff0000;">assemblies</span>&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">assembly=</span><span style="color: #800000;">"PhotoShare.UI"</span> /&gt; /<span style="color: #008000;">/Whatever the actual UI project is</span>
        &lt;/<span style="color: #ff0000;">assemblies</span>&gt;
      &lt;/<span style="color: #ff0000;">compilation</span>&gt;
      &lt;<span style="color: #ff0000;">pages</span> <span style="color: #0000ff;">automaticEncoding=</span><span style="color: #800000;">"false"</span>&gt; <span style="color: #008000;">//If you want it to auto HTML encode post/get stuff</span>
        &lt;<span style="color: #ff0000;">namespaces</span>&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">namespace=</span><span style="color: #800000;">"System"</span>/&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">namespace=</span><span style="color: #800000;">"System.Collections.Generic"</span>/&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">namespace=</span><span style="color: #800000;">"System.Linq"</span>/&gt;
          &lt;<span style="color: #ff0000;">add</span> <span style="color: #0000ff;">namespace=</span><span style="color: #800000;">"System.Web.Mvc"</span>/&gt;
        &lt;/<span style="color: #ff0000;">namespaces</span>&gt;
      &lt;/<span style="color: #ff0000;">pages</span>&gt;
    &lt;/<span style="color: #ff0000;">spark</span>&gt;
</pre>
<p>Ok so the web config is ready.  Now what?</p>
<p>Well now you are going to create a master page.  That&#8217;s right you are.  Don&#8217;t fight me on this.  I&#8217;m way cooler than you.</p>
<p>There is a little directory structure hard coding going on since by default you have to have things in certain places for Spark.  Oh well.  All Master Pages go in a directory named &#8220;Layouts&#8221; in the &#8220;Views&#8221; directory.  So something like:</p>
<pre>  Views/Layouts/Application.spark
</pre>
<p>D&#8212; it.  Forgot about that little tid bit too.  Spark files have to be named .spark.  Well actually I think there&#8217;s a way to call them whatever you want, but lets just go with defaults for now smarty pants.</p>
<p>And for the hard part, the html for the master page.</p>
<pre>  &lt;<span style="color: #ff0000;">html</span>&gt;
    &lt;<span style="color: #ff0000;">head</span>&gt;
    &lt;/<span style="color: #ff0000;">head</span>&gt;
    &lt;<span style="color: #ff0000;">body</span>&gt;
      &lt;<span style="color: #ff0000;">div</span>&gt;
        &lt;<span style="color: #ff0000;">use</span> <span style="color: #0000ff;">content=</span><span style="color: #800000;">"Middle"</span> /&gt;
          aasdfasdfa
      &lt;/<span style="color: #ff0000;">div</span>&gt;
    &lt;/<span style="color: #ff0000;">body</span>&gt;
  &lt;/<span style="color: #ff0000;">html</span>&gt;
</pre>
<p>HOLY HECK THAT&#8217;S HARD!  Now there needs to be a controller.  So just create one in the controllers folder.  In my project it&#8217;s called this:</p>
<pre>  Controllers/SparkTestController.cs
</pre>
<p>And then go ahead and create a view for index.  Once you&#8217;ve done that, rename the extension from aspx to spark.  Now for the html:</p>
<pre>  &lt;<span style="color: #ff0000;">use</span> <span style="color: #0000ff;">master=</span><span style="color: #800000;">"Application"</span>/&gt;

  &lt;<span style="color: #ff0000;">div</span>&gt;
    &lt;<span style="color: #ff0000;">content</span> <span style="color: #0000ff;">name=</span><span style="color: #993300;">"Middle"</span>&gt;
        hi there
    &lt;/<span style="color: #ff0000;">content</span>&gt;
  &lt;/<span style="color: #ff0000;">div</span>&gt;
</pre>
<p>And that&#8217;s it really.  As you can see, the placeholder on the master page (use content=&#8221;Middle&#8221;) is referred to on the child page.</p>
<p>To make testing this page easy, I would suggest changing the routing in the Global.asax.cs file to:</p>
<pre>  routes.MapRoute(
          <span style="color: #800000;">"Default"</span>,
          <span style="color: #800000;">"{controller}/{action}"</span>,
          <span style="color: #0000ff;">new</span> { controller = <span style="color: #800000;">"SparkTest"</span>, action = <span style="color: #800000;">"Index"</span>}
</pre>
<p>And you should see something like:</p>
<pre>  hi there aasdfasdfa
</pre>
<p>Proving that both the master page and the child page are printing stuff out.</p>
<p>You might be wondering why you should do all of this?  If you aren&#8217;t, you are one hell of a lemming.  And not the cool kind like those little guys that blow themselves up for the betterment of the lemming collective.Â  You&#8217;re that stupid one the just sits there with its hand out shaking its head.</p>
<p>A quick example:</p>
<pre>  <span style="color: #dcea0a;">&lt;%</span>
    <span style="color: #0000ff;">if</span>(something.IsTrue)
    {
  <span style="color: #dcea0a;">%&gt;</span>
       &lt;<span style="color: #ff0000;">div</span>&gt; hihihihih &lt;/<span style="color: #ff0000;">div</span>&gt;
  <span style="color: #dcea0a;">&lt;%</span>
    }
  <span style="color: #dcea0a;">%&gt;</span>
</pre>
<p>Compared to:</p>
<pre>  &lt;<span style="color: #ff0000;">div</span> <span style="color: #0000ff;">if=</span><span style="color: #800000;">"something.IsTrue"</span>&gt; hihihihih &lt;/<span style="color: #ff0000;">div</span>&gt;
</pre>
<p>Small example, but I think its pretty obvious why the second is so much better.  And this is just scratching the surface on what spark does really.Â   I&#8217;d suggest <a href="http://sparkviewengine.com/documentation">looking here</a> for more.  I&#8217;d also suggest a new hair cut because&#8230; just wow.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>ByATool.com gets a shiny new tool!</title>
		<link>http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/</link>
		<comments>http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 14:03:01 +0000</pubDate>
		<dc:creator>Andre</dc:creator>
				<category><![CDATA[Website News]]></category>
		<category><![CDATA[Writing]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1287</guid>
		<description><![CDATA[A while back, we put up an offer to write for our blog.Â  Only one has risen to the top as someone having both the technical know-how and the razor sharp wit required to write on a site such as this. ByATool.com Readers&#8230; Amy. Amy&#8230; ByATool.com Readers. Amy is a magnificent geek and almost 10 [...]]]></description>
			<content:encoded><![CDATA[<p>A while back, we put up an offer to write for our blog.Â  Only one has risen to the top as someone having both the technical know-how and the razor sharp wit required to write on a site such as this.</p>
<p>ByATool.com Readers&#8230; Amy.</p>
<p>Amy&#8230; ByATool.com Readers.</p>
<p>Amy is a magnificent geek and almost 10 year veteran of server administration  and software development. She has worked at IBM, Concurrent Technologies  Corporation, and University of Pittsburgh Medical Center.  Currently,  she is doing custom SharePoint development connected with Team  Foundation Server and the ASP.NET MVC framework development using the Entity  Framework, C#, and jQuery.  She is currently living in Pittsburgh and  not happy at all about commuting into a city with 3 rivers because of  the many bridges and no serious commuter subway systems&#8230; Who plans  this stuff?</p>
<p>Welcome Amy!</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Data Annotations, MVC, and Why You Might Like Them</title>
		<link>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/</link>
		<comments>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 18:01:40 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Data Annotations]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1155</guid>
		<description><![CDATA[So if you were like me before I knew what Data Annotations were, you most likely would be thinking, &#8220;What are Data Annotations?&#8221;. Well I&#8217;m glad I can read your mind and therefore I am glad you asked. Now the fun part about this post is that I might have to admit I was wrong. [...]]]></description>
			<content:encoded><![CDATA[<p>So if you were like me before I knew what Data Annotations were, you most likely would be thinking, &#8220;What are Data Annotations?&#8221;.  Well I&#8217;m glad I can read your mind and therefore I am glad you asked.</p>
<p>Now the fun part about this post is that I might have to admit I was wrong.  Why would that be?  Well in <a href="http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/">this post</a> I suggested that validation rules would be set in the controller.  Turns out, there is possibly a better place, on the model itself.  How can this be done???  Well that&#8217;s what you&#8217;re about to find out.</p>
<p>Say you have a user create model:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> AddUserModel
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> UserName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Password { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> RepeatPassword { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Now you could have a method on the controller like:</p>
<pre>  <span style="color: #0000ff;">publi</span>c <span style="color: #008080;">ActionResul</span>t AddUser(<span style="color: #008080;">AddUserMode</span>l model)
  {
    <span style="color: #0000ff;">if</span>(IsValid(model))
    {
      ...
    }
  }</pre>
<p>Where you have to create the IsValid method for every model on the controller that you need to validate (And possibly on other controllers if you are sharing models between them&#8230;) Or you can have this:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> AddUser(<span style="color: #008080;">AddUserModel</span> model)
  {
    <span style="color: #0000ff;">if</span>(<span style="color: #008080;">ModelState</span>.IsValid)
    {
      ...
    }
  }</pre>
<p>And that is already built in so no validation method needed.  But how is that possible?  Attributes on the model or namely the ValidationAttribute class.</p>
<p>First off you have to include the System.ComponentModel dll in the project.  Simple enough.  Please say you know how to do that or do me a favor and remind yourself to blink. OK done?  Good.</p>
<p>Now you can use some of the built in attributes which is good.  Things like required are nice:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AddUserModel</span>
  {
    [<span style="color: #008080;">Required</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> <span style="color: #008080;">UserName</span> { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<p>There you go.  Now if the UserName is null or empty, the ModelState will no longer be valid and will fail this check:</p>
<pre>  <span style="color: #008080;">ModelState</span>.IsValid</pre>
<p>Now you might wonder what the error message will be for that?  Honest answer:  I have no f&#8211;king clue.  That&#8217;s why you can actually set it.  Those guys at Microsoft thought of everything.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AddUserModel</span>
  {
    [<span style="color: #008080;">Required</span>(ErrorMessage = <span style="color: #800000;">"ENTER A USERNAME IDIOT!"</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> UserName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<blockquote><p>The guys in the legal department have told me I have to note that your error message should change depending on your use and you shouldn&#8217;t use the one above.  Whatever.</p></blockquote>
<p>Now you might want to actually pass the errors back, and why wouldn&#8217;t you?  You&#8217;re a fine, upstanding, and thoughtful person and I lie like a crook.  The errors, if there are any, are in here:</p>
<pre>  ViewData.ModelState.Values</pre>
<p>And you can use two loops to get to all of them, but I think the parent loop will only run once.</p>
<pre>  <span style="color: #0000ff;">foreach</span> (<span style="color: #008080;">ModelState</span> state <span style="color: #0000ff;">in</span> ViewData.ModelState.Values)
  {
    <span style="color: #0000ff;">foreach</span> (<span style="color: #008080;">ModelErro</span>r error <span style="color: #0000ff;">in</span> state.Errors)
    {
      messageList.Add(error.ErrorMessage);
    }
  }</pre>
<p>Pretty nice huh?  Maybe if you&#8217;re an idiot who just learned about this.  For cool people like me, it&#8217;s old news.</p>
<p>What&#8217;s the point this?  If &#8220;this&#8221; is data annotations:  Well it helps move some of the validation off the controller if you are looking for a more &#8220;Fat model, skinny controller&#8221; design which I&#8217;m told is a good idea.  This also gets rid of all the validation methods and saves time because of it.</p>
<p>If &#8220;this&#8221; is your life?  I have no idea.  But if you&#8217;re to the point that you&#8217;re asking me about the meaning of your life, you are in some serious trouble.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC:  Quick Overview of Controller Structure</title>
		<link>http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/</link>
		<comments>http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 16:37:47 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1012</guid>
		<description><![CDATA[Wow, that&#8217;s a mouthful far as titles go, but couldn&#8217;t think of a better way to say it. Now what I&#8217;m about to go through is the &#8220;system&#8221; I have found that works pretty well when it comes to structuring controllers knowing that there will be asynchronous operations. Why is that a big deal? Well [...]]]></description>
			<content:encoded><![CDATA[<p>Wow, that&#8217;s a mouthful far as titles go, but couldn&#8217;t think of a better way to say it.  Now what I&#8217;m about to go through is the &#8220;system&#8221; I have found that works pretty well when it comes to structuring controllers knowing that there will be asynchronous operations.  Why is that a big deal?  Well where you put certain methods can depend on which controller actually owns the action.</p>
<p>When I started using MVC, I had some issues on figuring out how to build controllers so that they made sense from a structural point of view.  <a href="http://byatool.com/index.php/pontification/what-i-hate-about-programming/">I slightly touched on it</a> but I wanted to show where I progressed to in the vain hope that I can help prevent stumbling on your part.</p>
<p>One thing to be noted is the asynchronous part.  I&#8217;ve become a firm believer that MVC is pointless without asynchronous operations.  Why?  Simply put, you can use them or you can come up with some annoying post and redirect for any create, update, or delete operations.  If you&#8217;re going to do that, you might as well just be institutionalized because you are one masochistic mother f&#8212;er.  For everyone else in the happy world, go with something like jQuery that makes it real easy to perform said operations.</p>
<p>With the last paragraph in mind, the part I had trouble with the most was figuring out where the actions go.  You see, when I started using MVC, I grouped stuff in an ultra simple manor.  Say I have a site for handling pictures.  Well there would be a view controller that would have anything to do with viewing images and an admin controller that took care of the uploading, changing, deleting, ecting.  As you can imagine, this was not what you might call ideal.</p>
<p>Once I got a feeling for MVC and how it worked, I started having things a little more separated but still didn&#8217;t feel right.  I had actions for viewing a list of images on the image controller no matter if public or admin side which wasn&#8217;t really ideal to me since it kind of blurred what was public and what was restricted from a conceptual point of view.  </p>
<p>It wasn&#8217;t until I started thinking in terms of unit testing that it started to make more sense.  If I were creating controllers as if they were classes instead of pages like with WebForms, maybe it would work out better.  Seems real profound right?  Well it was at the time since I still had WebForms state of mind.  All of a sudden, it made way more sense on how the controllers should be set up.  In an odd way, the controllers almost became almost business layer like.  If I wanted to update an Image, there would be an Update method on the image controller responsible for taking in the changes, validating, and dealing with the entity objects.  Everything that had to do strictly with displaying information would be handled by a display controller like the before mentioned Admin controller.  So something like:</p>
<pre>
<img src="http://www.iamwebproject.com/PhotoView/Photo/ShowPhoto/14" alt="Controller Outline" />
</pre>
<p>As you can see, the Admin controller has something to show all users.  The User controller has the methods for things like updating, creating, and validation.  Basically anything that would change an image is on one controller.  Anything for showing it on the main section controller.  That is, a controller that embodies an overall concept like say an Admin section of a site or possibly a controller for viewing galleries.  </p>
<p>The sequence of events (bad word choice&#8230;) would be something like:</p>
<p>Open Admin/UserList/<br />
Admin controller uses User Entity to retrieve list<br />
Admin View shows User List<br />
User clicks delete button/link on Admin View<br />
Javascript/jQuery method invoked to send id to User/Delete<br />
User controller receives id<br />
User controller validates id to make sure it is valid<br />
User controller validates current user to see if allowed to delete<br />
User entity Delete method invoked by User Controller<br />
Result of Delete Method is returned by User Controller (JSon preferably)<br />
Admin View displays the result</p>
<p>Treating controllers like classes (and the use of anonymous actions) allows a very clean separation of actions resulting in a nice logical layout.  Beyond this, it also allows for a greater separation between controllers which means its possible to do multiple parts of the entire project in parallel.</p>
<p>Maybe this is just stating the obvious, something I&#8217;m pretty good at, but my hope was to give a quick over view of laying out controllers for those who are just starting out.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC: Attibute to Check if Route Value Exists and&#8230; and Means Something!</title>
		<link>http://byatool.com/pointless/asp-net-mvc-attibute-to-check-if-route-value-exists-and-and-means-something/</link>
		<comments>http://byatool.com/pointless/asp-net-mvc-attibute-to-check-if-route-value-exists-and-and-means-something/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 12:48:31 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pointless]]></category>
		<category><![CDATA[Attributes]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=930</guid>
		<description><![CDATA[Get ready for a roller coaster ride around the insanity that is me. You might actually find it amusing but most likely you&#8217;ll just leave sick or underwhelmed. Don&#8217;t feel bad if you do, you wouldn&#8217;t be the first and, thanks to somehow being impervious to Natural Selection, you won&#8217;t be the last. Be proud. [...]]]></description>
			<content:encoded><![CDATA[<p>Get ready for a roller coaster ride around the insanity that is me. You might actually find it amusing but most likely you&#8217;ll just leave sick or underwhelmed. Don&#8217;t feel bad if you do, you wouldn&#8217;t be the first and, thanks to somehow being impervious to Natural Selection, you won&#8217;t be the last. Be proud.</p>
<p>Here&#8217;s what this post is about: Say you have a url like eh:</p>
<pre>/User/View/1</pre>
<p>Where 1 represents a UserId to a user that exists in some matter of context. (Does that makes sense?) Well there are a couple of things that could go wrong here. For one, if you don&#8217;t want to have a nullable id in your signature:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> View(<span style="color: #008080;">Int32</span>? userId)</pre>
<p>This could cause ouch:</p>
<pre>/User/View/</pre>
<p>But this problem is deeper. Much deeper. In fact so deep it deeper than even Piper Perabo has ever deeped before. Yrraaaahh!</p>
<p>What if the id doesn&#8217;t even refer to anything? Say the id is 101 but there&#8217;s no user with the id of 101? Beyond that, what if the id could be Id in some routes but UserId in others? WHAT WOULD YOU DO???</p>
<p>The idea here is to have something neato like this:</p>
<pre>  [<span style="color: #008080;">UserExistsById</span>]
  <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> View(<span style="color: #008080;">Int32</span> userId)</pre>
<p>And if that id is junk, then you redirect to an error page. Well if this sounds interesting, I&#8217;d be surprised, but read on in the event that it does.</p>
<p>Now this isn&#8217;t accomplished in the most simple manor, but for good reason: The more time in means the less time repeating. First method we need is something to simply check the route data to see if something exists:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">Boolean</span> RouteDataValueExists(<span style="color: #008080;">ActionExecutingContext</span> filterContext, <span style="color: #008080;">String</span> idToCheck)
  {
    <span style="color: #0000ff;">return</span> filterContext.RouteData.Values.ContainsKey(idToCheck);
  }</pre>
<p>Real easy. It either has been digested by MVC and regurgitated into some kind of route value or it hasn&#8217;t. Basically this is the first check. After all, if it doesn&#8217;t exist why bother going further?</p>
<p>Next is the method that will be calling this one. Mainly one that uses the RouteDataValueExists and if returns true, then it actually checks the value against where ever the user is persisted.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">Boolean</span> ValueFoundAndItemExists
  (
    <span style="color: #008080;">ActionExecutingContext</span> filterContext,
    <span style="color: #008080;">Enum</span> idToUse,
    <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">ActionExecutingContext</span>, <span style="color: #008080;">Enum</span>, <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">Int32</span>, <span style="color: #008080;">Boolean</span>&gt;, <span style="color: #008080;">Boolean</span>&gt; check,
    <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">Int32</span>, <span style="color: #008080;">Boolean</span>&gt; exists
  )
  {
    <span style="color: #008080;">Boolean</span> checksOut = <span style="color: #0000ff;">false</span>;
    <span style="color: #008080;">String</span> convertedId = idToUse.ToString();

    <span style="color: #0000ff;">if</span> (RouteDataValueExists(filterContext, convertedId))
    {
      checksOut = check(filterContext, idToUse, exists);
    }

    <span style="color: #0000ff;">return</span> checksOut;
  }</pre>
<p>Ok so kind of a lot at first and it&#8217;s hard to decide how to present this system, so just go with it.</p>
<pre>  <span style="color: #008080;">Enum</span> idToUse,</pre>
<p>This is a design choice. In reality this will be turned into a string anyhow, but the idea is it will be what to check the route values for. So if you are checking for UserId, you will pass in UserRequestTypes.UserId. Again this was a choice on my part as I hate passing text around.</p>
<pre>  <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">ActionExecutingContext</span>, <span style="color: #008080;">Enum</span>, <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">Int32</span>, <span style="color: #008080;">Boolean</span>&gt;, <span style="color: #008080;">Boolean</span>&gt; check,</pre>
<p>This is the method that will be used by ValueFoundAndItemExists to delegate out the actual checking if the id is an integer and is a real user.</p>
<pre><span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">Int32</span>, <span style="color: #008080;">Boolean</span>&gt; exists</pre>
<p>This will be the method that you will use to delegate the whole checking if it exists in the database. Something like:</p>
<pre>  <span style="color: #0000ff;">class</span> <span style="color: #008080;">User</span>
  {
    <span style="color: #0000ff;">public</span> Exists(<span style="color: #008080;">Int32</span> id)
    {
       <span style="color: #0000ff;">return</span> EntityContext.Context.User.Any(user =&gt; user.Id == id);
    }
  }</pre>
<p>Still with me? No? Greeeeat. Next up is the base class that contains the</p>
<pre>  <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">ActionExecutingContext</span>, <span style="color: #008080;">Enum</span>, <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">Int32</span>, <span style="color: #008080;">Boolean</span>&gt;, <span style="color: #008080;">Boolean</span>&gt; check,</pre>
<p>parameter from above.</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">abstract</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">BaseExistsAttribute</span> : <span style="color: #008080;">ActionFilterAttribute</span>
{
  <span style="color: #0000ff;">protected</span> <span style="color: #008080;">Boolean</span> Exists
  (
    <span style="color: #008080;">ActionExecutingContext</span> filterContext,
    <span style="color: #008080;">Enum</span> idToUse,
    <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">Int32</span>, <span style="color: #008080;">Boolean</span>&gt; exists
  )
  {
    <span style="color: #008080;">Int32</span>? id = <span style="color: #008080;">Convert</span>.ToString(filterContext.RouteData.Values[idToUse.ToString()]).ConvertTo&lt;<span style="color: #008080;">Int32</span>&gt;();
    <span style="color: #0000ff;">return</span> id.HasValue &amp;&amp; exists(id.Value);
  }
}</pre>
<p>Ok so something might look familiar like well basically all the parameters. The reason for this is that there is a little bit of delegate passing going on with this whole system. One method passes on methods to other method in some kind of crazy method hoe down without the flanel shirts.</p>
<p>You will notice the use of the enum in this part:</p>
<pre>  idToUse.ToString()</pre>
<p>Again, you can easily just pass in a string instead of an enum, I just did this to stay away from strings.</p>
<p>Only thing that might be of interest is the ToConvert method that you <a href="http://byatool.com/index.php/utilities/duck-typing-my-way-to-a-universal-string-convert/">can find here</a>. You don&#8217;t have to use it, you can simply just do a try parse on the</p>
<pre>  filterContext.RouteData.Values[idToUse.ToString()])</pre>
<p>To get an integer. That&#8217;s up to you. I could have just put that in the code for you to see but then I couldn&#8217;t randomly plug another post of mine.</p>
<p>Finally you have the actual attribute class:</p>
<pre>  [<span style="color: #008080;">AttributeUsage</span>(<span style="color: #008080;">AttributeTargets</span>.Method)]
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">QuoteExistsByQuoteId</span> : <span style="color: #008080;">BaseExistsAttribute</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnActionExecuting(<span style="color: #008080;">ActionExecutingContext</span> filterContext)
    {
      base.OnActionExecuting(filterContext);

      <span style="color: #0000ff;">if</span>
      (
        !<span style="color: #008080;">MvcMethods</span>.ValueFoundAndItemExists
        (
          filterContext,
          <span style="color: #008080;">UserRequestTypes</span>.UserId,
          Exists,
          <span style="color: #008080;">UserEntity</span>.Exists
        )
      )
      {
        filterContext.Result = <span style="color: #008080;">SiteMethods</span>.ErrorOut(<span style="color: #008080;">ErrorNames</span>.General_PageError);
      }
    }
  }</pre>
<p>And now it all comes together.</p>
<pre>  <span style="color: #008080;">UserRequestTypes</span>.UserId</pre>
<p>This is the enum I&#8217;ve been talking about this entire post! Now that I think of it, not really exciting.</p>
<pre>  Exists</pre>
<p>That&#8217;s the method on the base class that checks for everything.</p>
<pre>  <span style="color: #008080;">UserEntity</span>.Exists</pre>
<p>And that&#8217;s the method I need to check the persistence if the user is real. Remember? Takes in an integer and returns a boolean? Yes? Yes? No?</p>
<p>What&#8217;s ErrorOut? Again this is just a method I made to create an ActionResult that is an redirect to an error page. Not hugely important. It&#8217;s just what handles the situation when the value is bogus&#8230;. dude.</p>
<pre>  [<span style="color: #008080;">UserExistsById</span>]
  <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> View(<span style="color: #008080;">Int32</span> userId)</pre>
<p>And there you have it. Hopefully it was useful in some way but I&#8217;m not of touch with reality.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pointless/asp-net-mvc-attibute-to-check-if-route-value-exists-and-and-means-something/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC HtmlHelper Method for Creating Buttons With Forms and Optional Images: Part 1</title>
		<link>http://byatool.com/mvc/asp-net-mvc-htmlhelper-method-for-creating-buttons-with-forms-and-optional-images-part-1/</link>
		<comments>http://byatool.com/mvc/asp-net-mvc-htmlhelper-method-for-creating-buttons-with-forms-and-optional-images-part-1/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 18:01:55 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[Dynamic Controls]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=842</guid>
		<description><![CDATA[Straight from the &#8220;I made this and maybe you can find a use for it&#8221; bin, here is one of two ways I create image buttons. Why would you care? I have no idea, but two of the catches that comes with buttons is they have to be wrapped in a form and the fact [...]]]></description>
			<content:encoded><![CDATA[<p>Straight from the &#8220;I made this and maybe you can find a use for it&#8221; bin, here is one of two ways I create image buttons. Why would you care? I have no idea, but two of the catches that comes with buttons is they have to be wrapped in a form and the fact you have to, far as I know, <a href="http://byatool.com/index.php/utilities/asp-net-mvc-button-post-is-losing-querystring-values-and-getting-paramters-from-a-url/">add hidden value inputs to the form</a> to carry over the values from a url (Action of the form).  This take care of both, can ya&#8217; belee it?</p>
<p>This guy takes in a url (ie you already know what it should be, say from pre determined redirect value), breaks down the url to get the request parameters to make hidden inputs, and adds the button. Now I went with the image being a style for the button instead of passing in a location for the image itself, mostly because I find that to be easier to handle from a design perspective since it&#8217;s possible that particular image might be used a lot on a site. Seems easier, if you need to change the image, to change one css class then to have to search and replace a million image urls.  But what do I know?  No seriously, what do I know? </p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">String</span> OptionalImageButton(<span style="color: #0000ff;">this</span> <span style="color: #008080;">HtmlHelper</span> helper, <span style="color: #008080;">String</span> returnUrl, <span style="color: #008080;">Boolean</span> viewAsImage, <span style="color: #008080;">FormMethod</span> formMethod, <span style="color: #008080;">String</span> buttonText, <span style="color: #008080;">String</span> formClass, <span style="color: #008080;">String</span> imageClass, <span style="color: #008080;">String</span> buttonClass)
{
  <span style="color: #008080;">StringBuilder</span> html = <span style="color: #0000ff;">new</span> <span style="color: #008080;">StringBuilder</span>();
  <span style="color: #008000;">//Create the form along with the formMethod passed in</span>
  html.Append(<span style="color: #800000;">"&lt;form action=\"" + returnUrl + "\" class=\"" + formClass + "\" method=\"" + formMethod + "\"&gt; "</span>);

  <span style="color: #008000;">//This is the method</span> <a href="http://byatool.com/index.php/utilities/asp-net-mvc-button-post-is-losing-querystring-values-and-getting-paramters-from-a-url/">from this post</a><span style="color: #008000;">, it just give me all the hidden inputs from a url</span><span style="color: #008000;">
</span>  html.Append(<span style="color: #008080;">MvcMethods</span>.CreateHiddenValuesFromUrl(returnUrl));
  <span style="color: #008000;">//This is where you might hate me.  Instead of having an image for the button
</span>  <span style="color: #008000;">//I am using a css class to hold the image.  Just a choice, makes it easier
</span>  <span style="color: #008000;">//in my opinion</span>
  <span style="color: #0000ff;">if</span> (viewAsImage)
  {
    html.Append(<span style="color: #800000;">"&lt;input type=\"submit\" value=\"\" class=\"" + imageClass + "\" /&gt;"</span>);
  }
  <span style="color: #0000ff;">else
</span>  {
    <span style="color: #008000;">//If no image, then just put a text button.</span>
    html.Append(<span style="color: #800000;">"&lt;input type=\"submit\" value=\"" + buttonText + "\" class=\"" + buttonClass + " \" &gt;&lt;/input&gt;"</span>);
  }

  <span style="color: #008000;">//End the form</span>
  html.Append(<span style="color: #800000;">"&lt;/form&gt;"</span>);

  <span style="color: #0000ff;">return</span> html.ToString();
}</pre>
<p>You might notice the FormClass parameter, or maybe you didn&#8217;t because you can&#8217;t read.  If that&#8217;s the case, then we&#8217;re both wasting time.  However, if you did notice then you might find it odd.  As it is, a form has to be inline in order to show buttons next to each other. After all, by default a form is a block element like a div.  Therefore, the form itself will need a class or the style set.   Now I could default this to inline, but for the sake of giving power to the programmer, it&#8217;s left as a parameter. After all, maybe not all buttons should be inline.</p>
<p>And usage:</p>
<pre>  Html.OptionalImageButton(Model.ReturnUrl, Model.UserShowImages, <span style="color: #800000;">"Return"</span>, <span style="color: #800000;">"inline"</span>, <span style="color: #800000;">"returnButton"</span>, <span style="color: #800000;">"button080SmallTextAction"</span>)</pre>
<p>Pretty easy to use and clean&#8230; well clean for MVC at least. Next MVC post I&#8217;ll show the route driven version of this &#8220;control&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/mvc/asp-net-mvc-htmlhelper-method-for-creating-buttons-with-forms-and-optional-images-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC: Button Post Is Losing QueryString Values And Getting Paramters From A URL</title>
		<link>http://byatool.com/utilities/asp-net-mvc-button-post-is-losing-querystring-values-and-getting-paramters-from-a-url/</link>
		<comments>http://byatool.com/utilities/asp-net-mvc-button-post-is-losing-querystring-values-and-getting-paramters-from-a-url/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 14:43:18 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[QueryString]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=838</guid>
		<description><![CDATA[I was going to start this post with a rousing ARE YOU READY FOR SOME PROGRAMMING?, but my lawyer suggested it might cause the NFL to take action against me. He suggested something more simple like PROGRAMMING HAPPENS HERE! since he had high doubts the NBA will sue me. After all they&#8217;d have to admit [...]]]></description>
			<content:encoded><![CDATA[<p>I was going to start this post with a rousing ARE YOU READY FOR SOME PROGRAMMING?, but my lawyer suggested it might cause the NFL to take action against me. He suggested something more simple like PROGRAMMING HAPPENS HERE! since he had high doubts the NBA will sue me. After all they&#8217;d have to admit they actually came up with that f-ing slogan in the first place. It&#8217;s a win/win situation for me.</p>
<p>So one of the things I&#8217;ve run into with MVC is this situation&#8230; Say I have a form and a button, and the form has an action that looks like this:</p>
<pre>  &lt;<span style="color: #800000;">form</span> <span style="color: #ff0000;">action</span><span style="color: #0000ff;">="/Tools/AddTool/1?redirect=/Tools/ViewTool/1"</span> <span style="color: #ff0000;">method</span><span style="color: #0000ff;">="post"</span>&gt;
    &lt; <span style="color: #ff0000;">button</span> <span style="color: #ff0000;">type</span><span style="color: #0000ff;">="submit"</span>&gt;GO!&lt;/<span style="color: #800000;">button</span>&gt;
  &lt;/<span style="color: #800000;">form</span>&gt;</pre>
<p>Really simple. The idea is that I want to post to the AddTool action, do some stuff, then have the action redirect back to the ViewTool action. Seems like it should be easy right? Well not so much. Because when you view the ActionParameters (<a href="http://byatool.com/index.php/c/asp-net-mvc-attributes-and-semi-dynamic-check-for-request-parameters/">Like in this example</a>) for the &#8220;redirect&#8221; key, it finds the key but loses the value. This may result in a failure if have an attribute making sure it exists or possiblly you just have it set to a default that&#8217;s useless like a fourth foot. Either way, not good.</p>
<p>Now I haven&#8217;t figured out the reason for this (Don&#8217;t act so surprised, you aren&#8217;t a very good actor), but I have figured out a way around it. Basically for the form to keep the values, you need to add hidden values. I know, it&#8217;s a pain. Good thing I have a method that makes it easier. Also, this post is a prerequisite for a method I have for creating buttons&#8230; but that in the future.  ITS A TEASER! THIS POST IS A TEASER!  THERE I SAID IT!  CAN I GO NOW?</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">String</span> CreateHiddenValuesFromUrl(<span style="color: #008080;">String</span> baseUrl)
{
  <span style="color: #008080;">StringBuilder</span> html = <span style="color: #0000ff;">new</span> <span style="color: #008080;">StringBuilder</span>();

  <span style="color: #0000ff;">if</span>(!<span style="color: #008080;">String</span>.IsNullOrEmpty(baseUrl))
  {
    <span style="color: #008000;">//Have to find the ? to know where to begin</span>
    <span style="color: #008080;">Int32</span> indexOfQuestionMark = baseUrl.IndexOf(<span style="color: #800000;">'?'</span>);

    <span style="color: #008000;">//If the question mark exists and there is something after it, keep going
</span>    <span style="color: #0000ff;">if</span> (indexOfQuestionMark &gt; -1 &amp;&amp; baseUrl.Length &gt;= indexOfQuestionMark + 1)
    {
      <span style="color: #008000;">//Get everything AFTER the ?, something I didn't think of first time around
</span>      <span style="color: #008000;">//Caused many test failures and much shame to my family.
</span>      <span style="color: #008080;">String</span> request = baseUrl.Substring(indexOfQuestionMark + 1);

      <span style="color: #008000;">//Cut up the string by the &amp; since every parameter after the first
</span>      <span style="color: #008000;">//is divided by &amp;.. I know, Duh.
</span>      <span style="color: #008080;">String</span>[] splitList = request.Split(<span style="color: #800000;">'&amp;'</span>);

      <span style="color: #008000;">//Go through the list of possible request items
</span>      <span style="color: #0000ff;">foreach</span> (<span style="color: #0000ff;">var</span> requestItem <span style="color: #0000ff;">in</span> splitList)
      {
        <span style="color: #008080;">String</span>[] splitItem = requestItem.Split(<span style="color: #800000;">'='</span>);
        <span style="color: #008000;">//This is to make sure the parameter actually has a value to send in
</span>        <span style="color: #008000;">//the hidden values.  I supposed you could create an empty hidden
</span>        <span style="color: #008000;">//value to preserve the parameter, but remember the parameter
</span>        <span style="color: #008000;">//isn't being lost from the form action, just the value
</span>        <span style="color: #0000ff;">if</span> (splitItem.Length == 2 &amp;&amp; !<span style="color: #008080;">String</span>.IsNullOrEmpty(splitItem[1]))
        {
          <span style="color: #008000;">//Create a hidden input with the key name and the value
</span>          html.Append(<span style="color: #800000;">"&lt;input type=\"hidden\" name=\""</span> + splitItem[0] + <span style="color: #800000;">"\" value=\""</span> + splitItem[1] + <span style="color: #800000;">"\" &gt;"</span>);
        }
      }
    }
  }

  <span style="color: #0000ff;">return</span> html.ToString();
}</pre>
<p>And it&#8217;s just that simple. Mind you I could probably make this an extension method for the HtmlHelper, but I don&#8217;t really use it for that.</p>
<p>Next up will be more razzle and dazzle using this to make an optional image button. I bet you can&#8217;t wait. I know I can.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/asp-net-mvc-button-post-is-losing-querystring-values-and-getting-paramters-from-a-url/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC:  Attributes and Semi Dynamic Check for Request Parameters</title>
		<link>http://byatool.com/c/asp-net-mvc-attributes-and-semi-dynamic-check-for-request-parameters/</link>
		<comments>http://byatool.com/c/asp-net-mvc-attributes-and-semi-dynamic-check-for-request-parameters/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 00:46:59 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Attributes]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=803</guid>
		<description><![CDATA[If I were self involved I would say something silly like IN THIS AWESOME POST but I&#8217;m not. However in this post that is awesome I gave some examples of how to use attributes to set defaults or just check to see if an incoming id could be matched to a record somewhere&#8230; Sorry lost [...]]]></description>
			<content:encoded><![CDATA[<p>If I were self involved I would say something silly like <a href="http://byatool.com/index.php/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/">IN THIS AWESOME POST</a> but I&#8217;m not. However in <a href="http://byatool.com/index.php/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/">this post that is awesome</a> I gave some examples of how to use attributes to set defaults or just check to see if an incoming id could be matched to a record somewhere&#8230; Sorry lost my track of thought. Watching the begining of Transformers&#8230; You know the part where it could have been good.</p>
<p>Anyway, I figured I&#8217;d add another debatable use for an attribute, the CheckForGivenRequest one. Basically in the other post I had something that was specific it was checking for, this is used if you are checking for a request parameter but you don&#8217;t want to make an attribute for each and every one of them.</p>
<pre>  <span style="color: #008000;">//This is so you can use it many times on the same method</span>
  <span style="color: #008000;">//I know, I know... duh</span>
  [<span style="color: #008080;">AttributeUsage</span>(<span style="color: #008080;">AttributeTargets</span>.Method, AllowMultiple = <span style="color: #0000ff;">true</span>)]
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">CheckForGivenRequestAttribute</span> : <span style="color: #008080;">ActionFilterAttribute</span>
  {
    <span style="color: #008000;">//The constructor to set what should be looked for
</span>    <span style="color: #008000;">//Default amount is what it should be set if not there</span>
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">CheckForGivenRequestAttribute</span>(<span style="color: #008080;">String</span> requestParameterName, <span style="color: #008080;">Object</span> defaultAmount)
    {
      DefaultAmount = defaultAmount;
      RequestParameterName = requestParameterName;
    }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnActionExecuting(ActionExecutingContext filterContext)
    {
      base.OnActionExecuting(filterContext);
      <span style="color: #008000;">//Check the extra request parameters (ie &amp;someId=1) for if it exists
</span>      <span style="color: #008000;">//If it doesn't exist, then add it</span>
      <span style="color: #0000ff;">if</span> (!filterContext.ActionParameters.ContainsKey(RequestParameterName))
      {
        filterContext.ActionParameters.Add(RequestParameterName, <span style="color: #0000ff;">null</span>);
      }

      <span style="color: #008000;">//If it's null set to the default
</span>      filterContext.ActionParameters[RequestParameterName] =
         filterContext.ActionParameters[RequestParameterName] ?? DefaultAmount;
    }

    <span style="color: #008000;">//Just the properties, nothing to see here.  Go away...</span>
    <span style="color: #0000ff;">private</span> Object DefaultAmount { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">private</span> String RequestParameterName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>And then the use of it:</p>
<pre>  [<span style="color: #008080;">CheckForGivenRequestAttribute</span>(<span style="color: #800000;">"someStupidId"</span>, 1)]
  <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> INeedAnExample(<span style="color: #008080;">Int32</span> someStupidId)
  {
    ...
  }</pre>
<p>Now you might ask why not make that attiribute generic to avoid boxing.</p>
<p><strong>Why not make that attribute generic to avoid boxing?</strong></p>
<p>Glad you asked. Turns out that you can&#8217;t make attributes generic. Aparrently <a href="http://stackoverflow.com/questions/294216/why-does-c-forbid-generic-attribute-types">it&#8217;s somwhat debatable why</a> but not possible at the time being. Besides, the ActionParameters collection is &lt;<span style="color: #008080;">String</span>, <span style="color: #008080;">Object</span>&gt; anyhow, so at some point any stuct would be boxed anyhow.</p>
<p>On a side note, I never noticed this before, but when one of the non descript Autobots crashes near a pool, some kid is there to ask if he is the Tooth Fairy?  Seriously?  Are kids really that dumb?  Cause every picture I&#8217;ve seen of the Tooth Fairy has been a 20 foot tall metal thing with no discernible features.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/c/asp-net-mvc-attributes-and-semi-dynamic-check-for-request-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC: Attributes, ActionFilterAttribute, and Why You Might Want To Use Them</title>
		<link>http://byatool.com/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/</link>
		<comments>http://byatool.com/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 21:49:23 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Attributes]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=793</guid>
		<description><![CDATA[So if you&#8217;ve used MVC, and I know you have because you want to be cool like me, you&#8217;ve most likely run into an error like this: Certain parameter wasn&#8217;t found. Make [parameter] nullable. In other words, the parameter didn&#8217;t show up in the URL and therefor MVC can&#8217;t assign a value to it. This [...]]]></description>
			<content:encoded><![CDATA[<p>So if you&#8217;ve used MVC, and I know you have because you want to be cool like me, you&#8217;ve most likely run into an error like this:</p>
<blockquote><p>Certain parameter wasn&#8217;t found. Make [parameter] nullable.</p></blockquote>
<p>In other words, the parameter didn&#8217;t show up in the URL and therefor MVC can&#8217;t assign a value to it. This would of course happen with anything that isn&#8217;t nullable. Now you could do this:</p>
<pre>  <span style="color: #0000ff;">void</span> SomeAction(<span style="color: #008080;">Int32</span>? pageNumber)
  {
    <span style="color: #0000ff;">if</span>(someParameter.HasValue)
    {
      ..
    }
  }</pre>
<p>But do you really feel like putting that in every stupid method that happens to have the same parameter? Say the parameter is something simple like pageNumber. Taking the above code, you would have to see if pageNumber has a value and if it doesn&#8217;t, continue to set some variable to a default. Kind of annoying to have to repeat that over and over again when you know you will be looking for pageNumber on many actions. Well Attributes, or more importantly ActionFilterAttribute, are the way to get around this.</p>
<p>Say with the pageNumber example you want a default of 1 if it doesn&#8217;t exist. Well that&#8217;s easy to do, it would be something like this:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">CheckPageNumberAttribute</span> : <span style="color: #008080;">ActionFilterAttribute</span>
    {
        <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">const</span> <span style="color: #008080;">String</span> DefaultPageNumber = 0;

        <span style="color: #008000;">//This will fire automatically on page load.
</span>        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnActionExecuting(<span style="color: #008080;">ActionExecutingContext</span> filterContext)
        {
            base.OnActionExecuting(filterContext);
            <span style="color: #008000;">//ActionParameters.Values holds all the request parameters after the ? as in ?pageNumber=1</span>
            <span style="color: #008000;">//See if it exists first.  If not, add it</span>
            <span style="color: #0000ff;">if</span> (!filterContext.ActionParameters.ContainsKey(<span style="color: #800000;">"pageNumber"</span>))
            {
                filterContext.ActionParameters.Add(RequestConstants.PageNumber, <span style="color: #0000ff;">null</span>);
            }

            <span style="color: #008000;">//Set to default if it's not null</span>
            filterContext.ActionParameters[<span style="color: #800000;">"pageNumber"</span>] = filterContext.ActionParameters[<span style="color: #800000;">"pageNumber"</span>] ?? DefaultPageNumber;
        }
    }</pre>
<p>So the method looks more like this now:</p>
<pre>  [<span style="color: #008080;">CheckPageNumberAttribute</span>]
  <span style="color: #0000ff;">void</span> SomeAction(<span style="color: #008080;">Int32</span> someParameter)
  {
    ...
  }</pre>
<p>And you can now do your &#8230; without worry.</p>
<p>But what if the url is like this?</p>
<blockquote><p>ShowMeACoolRoom/Index/1/</p></blockquote>
<p>And you have your route set up like:</p>
<pre>  <span style="color: #800000;">{controller}/{action}/{roomId}</span></pre>
<p>And you want to make sure that not only does that userId exist in the url, but the user actually exists. Well you don&#8217;t look to the ActionParameters.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">sealed</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">RoomExistsAttribute</span> : <span style="color: #008080;">ActionFilterAttribute</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span> <span style="color: #0000ff;">void</span> OnActionExecuting(<span style="color: #008080;">ActionExecutingContext</span> context)
    {
      base.OnActionExecuting(context);

      <span style="color: #008080;">ChatRoom</span> foundRoom = <span style="color: #0000ff;">null</span>;
      <span style="color: #008000;">//RouteData.Values holds all the values in the url it was able to match to a route</span>
      <span style="color: #008000;">//Check the Values list in the RouteData for the id
</span>      <span style="color: #0000ff;">if</span>(context.RouteData.Values.ContainsKey(<span style="color: #800000;">"id"</span>))
      {
        <span style="color: #008000;">//Convert to an integer, ConvertTo <a href="http://byatool.com/index.php/utilities/duck-typing-my-way-to-a-universal-string-convert/">is just a method I've made</a>.</span>
        <span style="color: #008080;">Int32</span>? roomId =
          Convert.ToString(context.RouteData.Values[<span style="color: #800000;">"id"</span>]).ConvertTo();
        <span style="color: #0000ff;">if</span>(roomId.HasValue)
        {
            foundRoom = ChatRoom.GetRoomByID(roomId.Value);
        }
     }

     <span style="color: #008000;">//If the room isn't found, handle the error.</span>
     <span style="color: #0000ff;">if</span> (foundRoom == <span style="color: #0000ff;">null</span>)
     {
       <span style="color: #008000;">//redirect on error...</span>
       context.Result =
         <span style="color: #0000ff;">new</span> <span style="color: #008080;">RedirectToRouteResult</span>
         (
           GeneralConstants.RouteName,
           <span style="color: #0000ff;">new</span> <span style="color: #008080;">RouteValueDictionary</span>
           {
              { <span style="color: #800000;">"controller"</span>, <span style="color: #800000;">"sharedError"</span> },
              {  <span style="color: #800000;">"action"</span>, <span style="color: #800000;">"error"</span> },
              { <span style="color: #800000;">"name"</span>, <span style="color: #800000;">"someErrorKey"</span> }
            }
          );
       }
    }
  }</pre>
<p>Now the new method looks something like this:</p>
<pre>  [<span style="color: #008080;">RoomExistsAttribute</span>]
  [<span style="color: #008080;">CheckPageNumberAttribute</span>]
  <span style="color: #0000ff;">void</span> SomeAction(<span style="color: #008080;">Int32</span> roomId, <span style="color: #008080;">Int32</span> someParameter)
  {
    ...
  }</pre>
<p>And once again you are free to &#8230; without worry of the room not existing. Next post I plan on adding some more &#8220;advanced&#8221; attributes&#8230; hahaha advanced? This site? hahahaha sorry. But I will be adding a new post about certain attribute solutions I&#8217;ve found that work well.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/asp-net-mvc-attributes-actionfilterattribute-and-why-you-might-want-to-use-them/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC: Routes, Route Contraints, and My Love Hate Relationship</title>
		<link>http://byatool.com/lessons/aspnet-mvc-routes-route-contraints-and-my-love-hate-relationship/</link>
		<comments>http://byatool.com/lessons/aspnet-mvc-routes-route-contraints-and-my-love-hate-relationship/#comments</comments>
		<pubDate>Mon, 03 Aug 2009 16:29:05 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Routing]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=786</guid>
		<description><![CDATA[So something that has been somewhat of an uphill climb as of late is routing in MVC. I think part of it is the way it works and part of it is that I&#8217;ve approached MVC like a 10 year old with a new game; F- the instructions, I&#8217;m all up in this. What goes [...]]]></description>
			<content:encoded><![CDATA[<p>So something that has been somewhat of an uphill climb as of late is routing in MVC. I think part of it is the way it works and part of it is that I&#8217;ve approached MVC like a 10 year old with a new game; F- the instructions, I&#8217;m all up in this.</p>
<p><strong>What goes out must come in&#8230;</strong></p>
<p>The biggest misconception I had with routes is that the route definitions meant something when a page is loading. This is bad. Now before the nerd rage starts to build, I will qualify that statement. Route definitions mean nothing beyond a simple mapping of values. What? Well suppose I have two routes:</p>
<pre>   routes.MapRoute
   (
     ...
      <span style="color: #800000;">"{controller}/{action}/{roomId}/{name}"</span>,
     ...
   );</pre>
<p>and</p>
<pre>   routes.MapRoute
   (
     ...
     <span style="color: #800000;">"{controller}/{action}/{userId}/{name}"</span>,
     ...
   );</pre>
<p>Now on the way out, the system can find the route easy if you supply the correct route data: (Lets say for the second route)</p>
<pre>  routeValues = <span style="color: #0000ff;">new</span> <span style="color: #008080;">RouteDicationary</span>()
  routeValues.Add(<span style="color: #800000;">"controller"</span>, <span style="color: #800000;">"Room"</span>);
  routeValues.Add(<span style="color: #800000;">"action"</span>, <span style="color: #800000;">"Index"</span>);
  routeValues.Add(<span style="color: #800000;">"userId"</span>, 1);
  routeValues.Add(<span style="color: #800000;">"name"</span>, <span style="color: #800000;">"ProgramminTool"</span>);

  neededHelper.RouteUrl("SecondRoute", routeValues);</pre>
<p>Which will give me a wonderful address of:</p>
<pre>  /User/Index/1/ProgramminTool</pre>
<p>Awesome, the routing system did what I wanted. Problem is, I assumed too much coming in, ie when the page is loading from the url. (Say from a clicked link) I kept getting an error like:</p>
<blockquote><p>RoomId doesn&#8217;t exist. Make roomId nullable. Blah blah blah I hate you and you should quit programming and do something more equal to your ability level like spinning in circles.</p></blockquote>
<p>Though I might have take some artist license on the error, the meaning was simple: it was trying to run that url against the Room controller and it couldn&#8217;t find the roomId parameter in the request. Well that doesn&#8217;t make sense, after all it&#8217;s obvious that it should be looking for the user controller and use the route with the userId paramter. Sadly, it doesn&#8217;t work that way and not sure it could. Why? Well look at the url.</p>
<blockquote><p>/User/Index/1/ProgramminTool</p></blockquote>
<p>Now if you were too look at that, what would you think? You have four values, values that you can&#8217;t really guess the type since you have no real context. After all there could easily be a method that takes in a string userId as opposed to an integer userId. On top of that, it has no idea what the 1 is. There&#8217;s no userId=1 to tell it what it is. So what does it do? It goes down the route table and finds the best fit. Now you tell me, which does this url fit better?</p>
<pre>  <span style="color: #800000;">"{controller}/{action}/{roomId}/{name}"</span></pre>
<p>Or</p>
<pre>  <span style="color: #800000;">"{controller}/{action}/{userId}/{name}"</span></pre>
<p>It&#8217;s kind of a trick question since the answer is neither. It will just fit it to the first one that it likes, and in this example it&#8217;s the roomId one. Problem is, now the user controller method that is looking for the userId fails because there is no userId. Uhg.</p>
<p><strong>Computers are dumb, they can only do what we tell them.</strong></p>
<p>Fact is, in this situation I have to make some rules for the routing system to take in and start digesting the url properly, and there&#8217;s a way to do this: IRouteConstraint.</p>
<p>Say that you have certain controllers or actions you don&#8217;t want to use the first route. For this example I&#8217;ll use user actions from my current project. On the room index view there is a button for adding the room as a favorite. Now the action/method it needs is on the user controller, not the room controller. Therefore I have to post some information to the user controller using a route that looks like this:</p>
<pre>  <span style="color: #800000;">"{controller}/{action}/{userId}/{roomId}"</span></pre>
<p>But it is preceded by one that looks like:</p>
<pre>  <span style="color: #800000;">"{controller}/{action}/{id}/{name}"</span></pre>
<p>See the issue? Now when MVC generates the url, everything is fine. After all it uses the route name and the parameters to pick the correct route. On the way in, not so good. It naturally tries to conform the url to the id/name route. BOOM HEADSHOT! Now the solution.</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">NotGivenAction</span> : <span style="color: #008080;">IRouteConstraint</span>
{
  <span style="color: #008000;">//This is the action that we want to prevent from the route accepting</span>
  <span style="color: #0000ff;">private</span> <span style="color: #008080;">String</span> GivenAction { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

  <span style="color: #0000ff;">public</span> NotGivenAction(<span style="color: #008080;">String</span> givenAction)
  {
    GivenAction = givenAction;
  }

  <span style="color: #0000ff;">public</span> <span style="color: #008080;">Boolean</span> Match(<span style="color: #008080;">HttpContextBase</span> httpContext, <span style="color: #008080;">Route</span> route, <span style="color: #008080;">String</span> parameterName, <span style="color: #008080;">RouteValueDictionary</span> values, <span style="color: #008080;">RouteDirection</span> routeDirection)
  {
    <span style="color: #008080;">String</span> parameterValue = values[parameterName].ToString();
    <span style="color: #008000;">//Make sure the parameter exists and it doesn't match the bad action
</span>    <span style="color: #0000ff;">return</span> values.ContainsKey(parameterName) &amp;&amp; parameterValue != GivenAction;
  }
}</pre>
<p>The IRouteConstraint interface has a method Match that has to be given life. The short of it is take in the parameter name and find it&#8217;s value and then see if the value is the same as the action it&#8217;s looking for. For example, if I had an action of AddToFavorites, this would go through and make sure it isn&#8217;t that action. If it is, it knows to not use the current route for this action.</p>
<pre>routes.MapRoute
(
  <span style="color: #008080;">GeneralConstants</span>.RouteIdName,
  <span style="color: #800000;">"{controller}/{action}/{id}/{name}"</span>,
  <span style="color: #0000ff;">new</span> { controller = <span style="color: #800000;">"Room"</span>, action = <span style="color: #800000;">"Index"</span>, id = <span style="color: #800000;">"0"</span>, name = <span style="color: #800000;">"None"</span> },
  <span style="color: #0000ff;">new</span> { action = <span style="color: #0000ff;">new</span> <span style="color: #008080;">NotGivenAction</span>(<span style="color: #008080;">UserControllerConstants</span>.AddToUserFavorite) }
);

routes.MapRoute
(
  <span style="color: #008080;">GeneralConstants</span>.RouteUserIdRoomId,
  <span style="color: #800000;">"{controller}/{action}/{userId}/{roomId}"</span>,
  <span style="color: #0000ff;">new</span> { controller = <span style="color: #008080;">GeneralConstants</span>.ControllerUser, action =   <span style="color: #008080;">UserControllerConstants</span>.AddToFavorites, userId = <span style="color: #800000;">"-1"</span>, roomId = <span style="color: #800000;">"-1"</span> }
);</pre>
<p>So now it will skip the first and push to the second when the url looks like:</p>
<pre>  /User/routes.MapRoute/AddToFavorites/1/2/</pre>
<p>Take that you f-ing routes. KING KONG AIN&#8217;T GOT S- ON ME!</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/aspnet-mvc-routes-route-contraints-and-my-love-hate-relationship/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC:  Is the Use of jQuery/Asynchronous calls a Must?</title>
		<link>http://byatool.com/pontification/aspnet-mvc-is-the-use-of-jquery-asynchronous-calls-a-must/</link>
		<comments>http://byatool.com/pontification/aspnet-mvc-is-the-use-of-jquery-asynchronous-calls-a-must/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 20:22:57 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=765</guid>
		<description><![CDATA[In this wonderpost, I questioned the use of jQuery in the mind of the purist MVCist. (If that&#8217;s not a word yet, it is now and I expect royalties.) Now I&#8217;ll flip it tool style and ask it from another direction: Can MVC survive without jQuery? Here&#8217;s the situation: I have a site that I [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://byatool.com/index.php/pontification/are-jquery-and-asynchronous-calls-against-mvc/"><span>In this <span>wonderpost</span></span></a><span>, I questioned the use of <span>jQuery</span> in the mind of the purist <span>MVCist</span>. (If that&#8217;s not a word yet, it is now and I expect royalties.) Now I&#8217;ll flip it tool style and ask it from another direction: Can MVC survive without <span>jQuery</span>?</span></p>
<p><span>Here&#8217;s the situation: I have a site that I made a while back (Basically a phone friendly chat room emulator) that was kind of experiment on a couple levels, one being the use of Entity Framework and <span>WebForms</span>. (</span><a href="http://www.eythere.com">It&#8217;s here if you are curious</a>&#8230; right now you have to make an account though. Never got around to allowing non logged in users.) Another part was to see if I could make a multi phone compliant page that had to be fast and work on as many phones as possible. (Anything with a browser at least) And had to be touch friendly. (No links, just buttons)</p>
<p><span>A week back I decided, after trying to make new sites with MVC, to take an existing work and really give MVC a rugged test. <span>Eythere</span> was just that site. Now personally I thought this would be pretty simple since MVC seemed really good at simple, non business sites. What could be more simple than a chat room emulating site that has no javascript? (Aside from whatever Javascript <span>WebForms</span> use for <span>postbacks</span>) I mean in the end, it&#8217;s just a bunch of buttons right?</span></p>
<p>Yeah turns out what those buttons did was at the heart of my issues. You see, with WebForms, everything done on a page is meant for that page. Sure you can defer how things are handled from the page to another tier, but the action itself belongs to the page. For example, say that a user wanted to make a room a favorite, well there&#8217;s a button named favorite that he/she clicks to do so.</p>
<pre>
 <img class="alignnone size-full wp-image-766" title="Oh the lovely colors."  src="http://byatool.com/wp-content/uploads/2009/07/bat_chatbox1.png" alt="Oh the lovely colors." width="429" height="222" />
</pre>
<p><span>In <span>webforms</span>, the Room.<span>aspx</span> page would handle the Favorite button click and the current user&#8217;s favorite list would have the room removed or added depending. But the call to the add/remove would be handled by the button&#8217;s click event and then the page would be reloaded. Something we in the know call &#8220;easy&#8221;. (Like that word? Use it. It&#8217;s free because I&#8217;m such a nice guy) </span></p>
<p><span>Now with MVC it&#8217;s a whole new ballpark. With controllers, it becomes of question of what controller should handle this. It could go onto the room controller, but in the end it deals with a user and adding something to the user. So it&#8217;s fair to say that this is probably a job for Superman if Superman happens to be a <span>UserController</span> or you&#8217;ll most likely end up repeating code.</span></p>
<p>Now the issue: How is this handled? Whether link or button, something has to be posted to the user controller. Posting to the controller means that the controller, on finish, has to create a model and send it to a view. Well this kind of sucks doesn&#8217;t it? The user clicks the + Favorite button and bam is taken to a whole new page.</p>
<blockquote><p><strong>SURPRISE IT&#8217;S BEEN ADDED TO YOUR FAVORITES! </strong></p></blockquote>
<p><span>Not what I would call fluid. The other thought it to have a redirect, which in the end is more fluid in that it takes the user back to the original page BUT with that you have to send a lot of information back and forth. After all, in MVC a lot of the information for a given &#8220;page&#8221; is passed using get. So for instance you have a room with a <span>roomid</span> and a page number and a count of items to show and possibly a sort you&#8217;re looking at:</span></p>
<p>/Room/1/?pageNumber=1&amp;amountToShow=5&amp;sort=Date</p>
<p><span>Which means all of that has to be sent to the User controller in order to save the state, has to be put in session/some kind of user cache, or you just send the entire <span>url</span>. In any case, something has to be tossed around for this to work. More seamless than the other way but it is a lot of work for something so simple.</span></p>
<p><strong>When it comes to ease of UI design, jQuery/asynchronous  operations are a must.</strong></p>
<p><span>Something I think that the MVC idea fails at it in a UI sense it was makes it strong in a programming sense, logical separation of tasks. Right off the bat, I hated the way <span>WebForms</span> handled </span><a href="http://byatool.com/?p=351">AJAX &#8220;web methods&#8221;</a>. Having to repeat methods per page so they could be &#8220;registered&#8221; was ugly and a pain. MVC and it&#8217;s separation/REST ways makes <a href="http://byatool.com/index.php/ui/aspnet-mvc-jquery-json-and-paging-hows-that-for-a-soe-title/"><span><span>asynchronous</span> calls so easy</span></a><span>. However, what used to be a simple operation in <span>WebForms</span> has now become cumbersome without outside help. Straight up, it seems impossible to do non drill down design without using <span>jQuery</span> or some kind of javascript library equivalent without killing the separation that MVC seems to embrace. </span></p>
<p><span>Why is this a problem? For the most part it isn&#8217;t. Most people aren&#8217;t going to try something like <span>EyThere</span> (Wouldn&#8217;t recommend it, it was a pain) since how many people create sites with multiple phones in mind? However, it does serve to show what seems to be a glaring annoyance with MVC. Either use asynchronous calls or just sink.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/aspnet-mvc-is-the-use-of-jquery-asynchronous-calls-a-must/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC Issue:  Form With Get Method Not Passing Request Values</title>
		<link>http://byatool.com/net-issues/aspnet-mvc-issue-form-with-get-method-not-passing-request-values/</link>
		<comments>http://byatool.com/net-issues/aspnet-mvc-issue-form-with-get-method-not-passing-request-values/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 19:46:49 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[.Net Issues]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=759</guid>
		<description><![CDATA[DISCLAIMER: This has a solution but there has to be a better way. So I came across a really odd situation with the MVC framework today, and I&#8217;m on the edge of some serious Nerd Rage. Here&#8217;s the issue: I have a route that looks like this: "{controller}/{action}/{roomId}/{name}" And a form that looks like this: [...]]]></description>
			<content:encoded><![CDATA[<p><strong>DISCLAIMER: This has a solution but there has to be a better way.</strong></p>
<p>So I came across a really odd situation with the MVC framework today, and I&#8217;m on the edge of some serious Nerd Rage. Here&#8217;s the issue:</p>
<p>I have a route that looks like this:</p>
<pre>  <span style="color: #800000;">"{controller}/{action}/{roomId}/{name}"</span></pre>
<p>And a form that looks like this:</p>
<pre>  <span style="color: #800000;">&lt;form</span> <span style="color: #ff0000;">action</span><span style="color: #0000ff;">="Room/Index/6/SomeThing?pageNumber=1&amp;amountToShow=5"</span> <span style="color: #ff0000;">method</span><span style="color: #0000ff;">="get"</span>&gt;
   &lt;<span style="color: #800000;">button</span> <span style="color: #ff0000;">type</span><span style="color: #0000ff;">="submit"</span>&gt;SomeButton&lt;<span style="color: #800000;">/</span><span style="color: #800000;">button</span>&gt;
  &lt;<span style="color: #800000;">/form</span>&gt;</pre>
<p>Can&#8217;t get much simpler&#8230; or is it more simple? Whatever. Point is, when the the button is clicked, it should go to that page like the form action says to. And it does, sort of. For some reason it ends up stripping the values from the pageNumber and amoutToShow request variables. How do I know this? Well break points at certain times show me that the current ActionExecutingContext ActionParameters (the thing that stores all the request parameters) has the two I need but neither has a value. And since they are not included in that route description, it must see them in the url.</p>
<p>You might think it has to do with forms and submitting, and it might except here&#8217;s the kicker&#8230; with a route like this:</p>
<pre>   <span style="color: #800000;">"{controller}/{action}/{roomId}/{name}/{pageNumber}/{amountToShow}"</span></pre>
<p>All of a sudden it can see the values. Mind you the url ends up like:</p>
<pre>  Room/Index/1/Something/1/5</pre>
<p>Which you would expect from the route definition. To add to the fun, if I add hidden values:</p>
<pre>  &lt;<span style="color: #800000;">form</span> <span style="color: #ff0000;">action</span><span style="color: #0000ff;">="Room/Index/6/SomeThing?pageNumber=1&amp;amountToShow=5"</span> <span style="color: #ff0000;">method</span><span style="color: #0000ff;">="get"</span>&gt;
    &lt;<span style="color: #800000;">input</span> <span style="color: #ff0000;">type</span><span style="color: #800000;">="hidden"</span> <span style="color: #ff0000;">name</span><span style="color: #800000;">="pageNumber"</span> <span style="color: #ff0000;">value</span><span style="color: #800000;">="1"</span> /&gt;
    &lt;<span style="color: #800000;">input</span> <span style="color: #ff0000;">type</span><span style="color: #800000;">="hidden"</span> <span style="color: #ff0000;">name</span><span style="color: #800000;">="amountToShow"</span> <span style="color: #ff0000;">value</span><span style="color: #800000;">="5"</span> /&gt;
    &lt;<span style="color: #800000;">button</span> <span style="color: #ff0000;">type</span><span style="color: #800000;">="submit"</span>&gt;SomeButton&lt;<span style="color: #800000;">/button</span>&gt;
  &lt;<span style="color: #800000;">/form</span>&gt;</pre>
<p>It works with the original route.  Doesn&#8217;t really make sense to me, but my understanding of the system isn&#8217;t exactly expert level.  However, I could buy this if the hidden field method worked and the extended route definition didn&#8217;t.</p>
<p>For now I can use the hidden input method since there&#8217;s no issue with showing the parameters.  Just not what I&#8217;d call &#8220;Best solution&#8221; types stuff.</p>
<p>Sigh.  MVC :  One step forward, two steps back.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/net-issues/aspnet-mvc-issue-form-with-get-method-not-passing-request-values/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

