Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
[PSA] Using the Code Behind in MVC causes blindness

Ok, maybe the title to this post was a little misleading, there have been no studies that actually prove that one way or another if will actually go blind using a CodeBehind, but there have been studies (ok, may just suggestions) that you should NOT use the CodeBehind in a MVC application (for anything other than strongly typing your ViewData).

In standard Asp.net WebForms development the CodeBehind was meant to act as a page controller, but over the years it has turned more into a dumping ground for all sorts of evil code (ie business logic).  It is this nasty, ugly code that has given (in part) WebForms a bad image.  By continuing to use your code behind in MVC all you are really doing is taking an old nasty technique and applying it to new framework and in turn removing one of the great advantages of MVC.

Part of the beauty of the MVC pattern (notice I said pattern, not framework) is that it helps to enforce Separations of Concerns by pushing logic out of your view and into your controllers.


Side Bar

The controller is NOT to be used in the same manner as Code Behinds in WebForms.  The controller should only be responsible for either directional logic or conditional logic.

What is Directional logic? Directional logic is any logic whose role is to determine how and where data should be gathered base on criteria provided by the routed request.

What is Conditional logic?  Conditional logic is any logic that will attempt to perform various if/else style checks to determine how to best handle the routed request.


If you find yourself using the codebehind for anything OTHER than strongly typing your ViewData you are probably doing something WRONG.

Here are a few rules to live by when doing MVC

  1. Keep your Code Behind empty
  2. Keep your Views simple
  3. Keep your Controllers light
  4. Keep your Model fat (domain model that is)

Till next time,

[--- Check out www.dimecasts.net ---]


Posted 12-12-2008 7:38 AM by Derik Whittaker

[Advertisement]

Comments

Tim Barcz wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-12-2008 8:44 AM

Good advice and I'm glad someone said it....

As a developer if you're working with this new framework you find yourself doing some of the things that Derik is ranting about you have to have the discipline and professionalism to stop yourself.  

If ever in doubt about whether you're putting too much code somewhere or in the wrong place, ask yourself if you can test it.  Even if you aren't testing....ask yourself, how you would test it.  If your code leaves you unsure and scratching your head, that may be a sign you've put code somewhere that, while works, is now legacy code a la Michael Feathers (code that isn't tested).

DotNetKicks.com wrote [PSA] Using the Code Behind in MVC causes blindness
on 12-12-2008 9:05 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Lerxst wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-12-2008 10:20 AM

Looks like people now (myself included) is realizing that ASP.NET MVC by itself is no guarantee of better systems; people can mess up with it just as bad as people can mess up with "classic" ASP.NET webforms.

So, of the 3 most commonly referred advantages of ASP.NET MVC - testability, control over HTML and separation of concerns - I would say the third one depends on the coder just as usual.

Steven Harman wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-12-2008 11:50 AM

@Lerxst - re:SOC being a case of "it depends"

Clearly there is no magic bullet - or framework/toolkit/etc... - that can fix or make up for irresponsible software developers. :)

ASP.NET MVC Archived Buzz, Page 1 wrote ASP.NET MVC Archived Buzz, Page 1
on 12-12-2008 5:13 PM

Pingback from  ASP.NET MVC Archived Buzz, Page 1

Brian Johnson wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-12-2008 8:41 PM

Well it's like I've always said - a pattern/tool/framework does not a good program make...

Thanks for pointing out the elephant in the room; let's hope people listen!

Derik Whittaker wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-12-2008 8:59 PM

@Brian,

Yes it is the elephant in the room, but my co-author Chris (subjunctive.wordpress.com) was telling me about an MVC app he ran across at a client that had tons of logic in the code behind and I had to post something on why that is evil.

Kirk Clawson wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-12-2008 10:52 PM

Agreed, especially on the point about controller != code behind. Unfortunately, a lot of the journeyman devs out there hearing about this great new Microsoft Framework called EmVeeSee look up ScottGu's demo code, and think it's Holy Writ to do all of that stuff in thier action methods...

> Create Linq2SQL context - check

> Query context - check

> Fill in entity object - check

> Save back to context - check

> Redirect to action - check

That's not a knock against Gu. It's just demo code after all, but I think I'd like to see the MS crew be a little more vocal with disclaimers like "THIS IS NOT HOW YOU'RE REALLY SUPPOSED TO DO THIS. I'M DOING BAD THINGS HERE."

EricTN wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-13-2008 12:26 AM

Getting this kind of great guidance makes me anticipate your MVC book even more.  I'll be interested in the "how" of things, but "best practices" is also something dev's should understand and embrace.  Cheers!

Dave Schinkel wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-16-2008 11:10 AM

You will obviously use "some" code behind such as in your Page_Load but you want to keep it to a minimum and have your controllers do the work as much as possible.

Derik Whittaker wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-16-2008 11:54 AM

@Dave,

No, would not even use a page_Load

Troy Goode wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-16-2008 7:43 PM

I'd take it a step further and say that when possible you should REMOVE the codebehind. YAGNI. Hope you don't mind the self-link, but I feel this is relevant to the discussion:

www.squaredroot.com/.../MVC-Strongly-Type-ViewPages-Without-A-Code-Behind.aspx

Cody Skidmore wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-17-2008 10:01 AM

I agree with fervor -- one point though.

In order to use WebForm controls, it is (as far as I know) necessary to use limited code to state the WebForm control in the code behind file.

I'm using MSChar, DevExpress's GridView & Tab control in a MVC app.  The only way I was able to bind data to the chart & grid was to add an OnLoad event to the view's code behind file and bind data sources there.

This however, is the only code in the file.  If you or anyone else has a suggestion for handing this situation better, please post about it.

Derik Whittaker wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-17-2008 10:05 AM

@Cody,

I would not use webform controls in MVC as MOST of them use postback and server controls

Cody Skidmore wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 12-17-2008 3:54 PM

@Derik

Yes, it is true.  WebForm controls depend on both the Postback and ViewState models.  

You may also be aware that not using 3rd party controls or web form controls in general is a show-stopper for enterprise environments like I work in.

I'm not disagreeing with you.  ASP.NET MVC's philosophy makes perfect sense to me as an engineer.  However, If my company cannot leverage Webform controls at all, they'll elminate this framework completely.

To work with ASP.NET MVC,  my choices are:

- work-arounds and putting the two together.

- find another flexible company that understands the advantages of ASP.NET MVC.

The later isn't realistic IMO -- although I'd code for food if necessary.  :-)

Mark Melville wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 01-02-2009 6:50 PM

I was suprised to find that MVC encourages <% %> in the markup.  I found this article searching for how to use asp.net server controls with MVC.  After tinkering with my own MVC app, I'm thinking: "They went to all this trouble for separation of concerns, but then went back on .net's first separation of concerns, namely separating markup from code.  This is a big deal if you have a non-developer maintianing your markup (i.e. a designer).

Rather than do this:

<input type="text" name="Title" value="<%=ViewData["FirstName"] %>" />

What about this:

MARKUP:

<input type="text" name="FirstName" runat="server" id="FirstName" />

CODE BEHIND:

public void Page_Load(object sender, System.EventArgs e)

{

    FirstName.Value = ViewData["FirstName"];

}

So what do you think of using the HTMLGeneric Controls?  it does not generate viewstate or postbacks, yet it leaves the markup to layout the page and code to determine what values go in what fields.  In my mind, this is not domain business logic, but it is the view's business logic and so SHOULD go into a code-behind.

Mark

p.s. I'm using this tip to remove the .net control tree id from form posts: code.msdn.microsoft.com/.../ProjectReleases.aspx

Mark

Burns wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 01-05-2009 8:48 AM

I disagree - as long as the codebehind is only used for simple view logic, I think it's fine.

Say my strongly-typed model is IEnumerable<User>, where User is:

string Username

string FullName

UserType Type

Then in my view I want to iterate through the IEnumerable and display the User details in a table.  I want to display each row in the table using a different colour/cssclass depending upon the UserType.

Three options spring to mind:

Use a different model with a CssClass property and put the css selection logic in the controller - IMO this is placing View code in the controller.

Place the logic in the ASPX file along with the HTML - messy.

Create a GetCssClassFromUserType() method in the codebehind file and call it from the ASPX - nice.

Feelings?

Jereme wrote re: [PSA] Using the Code Behind in MVC causes blindness
on 01-30-2009 8:08 PM

I've found that I really like using the code behind in ASP.NET MVC. I have a standard structure for how I want my forms laid out. If I build the form in the code-behind, I can re-use a bunch of stuff and have my UI compile-time checked. This also makes it much easier to update the site structure; there's only one place my data entry row is defined.

The aspx content ends up looking like this:

<%= form %>

and the aspx.cs file ends up having this in the onload:

var formItems = new IFormItem {

   Item1,

   Item2,

   Item3

}

form = Html.BuildForm<Controller>(c => c.Method(), "FormName, formItems);

This has been quite handy ... so I guess it all depends on what you're doing in the code behind.

card recovery wrote card recovery
on 10-12-2013 11:02 AM

sd card recovery pro is ranked in the top as it is a leading sd card recovery software for many kinds of memory cards.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)