Code Blocks vs. Code Behind

Rate It (1)

Last post 04-03-2008 11:21 PM by pure.krome. 31 replies.

Sort Posts:

  • Re: Code Blocks vs. Code Behind

    03-28-2008, 2:29 PM
    • Loading...
    • jbardrof
    • Joined on 03-22-2007, 11:47 PM
    • Naples FL
    • Posts 190

    I can give one very HUGE reason why I'm looking forward to not using server controls.  They outputted some truly ugly stuff.  I'm sure I'm not the only one who cringed when he realized that gridviews outputted tables.  /shudder.  With MVC its very easy for me to create a fully CSS based repeating structure. Whats the advantage?

     
    Well when you hand off the code to a graphic designer they don't need to know how <asp:... /> tags work in order to style the page.  When it comes to a true web based app, it was usually tough to hand off the view to a designer and tell them to make it look pretty unless they knew how to handle asp tags. Now they keep the data output structures and can fully manage the html/css to really get seperation.  Your form has no bearing on function.  With webforms form is injected into function because your functional asp tag needs to address the form.  ick.

     
    If thats not enough, here is a little example I whipped up as to why i'm happy not to have gridviews.

     
    lets look at a gridview

     
     

    <asp:GridView ...>
    <Columns>
    <asp:BoundField DataField="Value" />
    </Columns>
    </asp:GridView>

     

     From there in your code behind we all know what you have to do, but lets say you have a field that you want to say change the color of the text dynamically. Well then we have to hook up to the rowdatabound event, check for the incoming data, find the right cell... as we all know, it gets very wordy, and takes quite an amount of code to iterate through the data structure. 

    So how can we do this better with MVC?  well take a look, first yes, I know I said I like CSS better, but for simplicity, we're using a table here:

     

    <table>
    <tr>
    <td>Name</td>
    <td>Value</td>
    <td>Edit</td>
    </tr>
    <%foreach (elements el in ViewData)
    {%> <tr>
    <td><%=el.Name%></td>
    <td><%=checkValue(el.Value)%></td>
    <td><%=Html.ActionLink("Edit", "Edit", new{ name = el.Name }) %></td>
    </tr>
    <% } %> </table>
      

      

    public string checkValue(double value)
    {
    if (value > 0)
    {
    return "<span style=\"color:green\">" + value + "</span>";
    }
    else { return "<span style=\"color:red\">" + value + "</span>";
    }
    }

     
     We add the method to the codebehind, yes, when we want to perform logic in our View we can use methods in the codebehind. And really, isnt this so much cleaner than a gridview? we can explicitly state our concernse, and follow the code.  This is faster too, because you get rid of the overhead from the gridview.  At first I felt that inline code was bad, but the more I work with it I realize the control we now have over our output is so much better.

     
     

    Remember if you have gotten your answer to mark your thread as answered.
  • Re: Code Blocks vs. Code Behind

    03-28-2008, 2:52 PM
    • Loading...
    • DavidKiff
    • Joined on 12-07-2006, 11:07 PM
    • Hertfordshire, UK
    • Posts 1,633

    @jbardrof

    The MVC Framework seems to be a great for people who dont want to learn how to use WebForms and strugle to understand the page cycle etc!  The MVC model is much simpler to use. 

    As for your gridview comment.... im not sure I follow!  Ill give you a quick example of how to do it using the same approach you have used for MVC.

    <asp:GridView runat="server" CssClass="test" ID="test">
        <Columns>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <%=checkValue(Eval("el.Value")%>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Value" DataField="el.Value" />
            <asp:BoundField HeaderText="Edit" DataField="el.Edit" />
        </Columns>
    </asp:GridView>

     Less lines of code!! No foreach logic within the markup!  The only advantage I can see that the MVC view has is type-safty!  If you really want complete control over you code why not use a repeater?  That is the reason they are designed!!

    jbardrof:
    realized that gridviews outputted tables.  /shudder

    Tables are for tabular data.. thats what they have been created for!! XHTML 1.0 standards and WC3 has no problems with the use of tables!!  Tables for layout.... yuk...

    If your putting data that is not tabular into the gridview your probably using the wrong control!!

    David Kiff
    http://DavidKiff.co.uk

    -- "Mark As Answer" If my reply helped you --
  • Re: Code Blocks vs. Code Behind

    03-28-2008, 3:01 PM
    • Loading...
    • DanFinch
    • Joined on 03-19-2008, 7:45 PM
    • Posts 11

    When I first took a look at ASP.NET MVC I was wary of the inclusion of .aspx but after working with it for a while I'm beginning to favor spaghetti code in MVC. In web forms it quickly got hairy and there's every opportunity to avoid unreadable nonsense entirely in MVC (helpers), but it's a great templating solution for people who want to work intimately with the standards, but I've found use for view-specific helper methods in code-behind which use System.Web.UI.HtmlControls. It depends on the view.

  • Re: Code Blocks vs. Code Behind

    03-28-2008, 3:16 PM
    • Loading...
    • ShaneBauer
    • Joined on 06-16-2002, 12:04 PM
    • Maryland
    • Posts 82

    Honestly, I stopped reading your post after the first sentence. The last part is correct, though. "The MVC model is much simpler to use." That's right. HTTP is simple, so why shouldn't the application framework be simple as well. There is no such thing as a page life cycle in HTTP. You have a responses and requests. Why should WebForms have numerous events for a single page?

     WebForms is Windows forms for the Web (hence the name). WebForms wasn't created for smart people to show off their understanding of events.

     Again, MVC isn't for everyone. If you don't see the benefits, then don't use it. Not everyone will like it. Spending two pages on a forum trying to tell someone why they should use a tool isn't beneficial for anyone. Coming here to spark debate and learn is one thing, but saying that a certain tool is only for people that can't understand another is ridiculous.
     

    Shane Bauer
    MCP - ASP.NET

  • Re: Code Blocks vs. Code Behind

    03-28-2008, 4:21 PM
    • Loading...
    • DavidKiff
    • Joined on 12-07-2006, 11:07 PM
    • Hertfordshire, UK
    • Posts 1,633

    ShaneBauer:
    Honestly, I stopped reading your post after the first sentence

    You read the end Smile

    ShaneBauer:
    so why shouldn't the application framework be simple as well

    Why should it not!?  To behonest as ive already said I like the MVC Framework, even written some sites in it already Big Smile!  The debate im raising (educational) is it good that markup and code is mixed together?

    I have come from a classic asp background into .NET and yes in the begining I struggled to understand why its better especially with the lack of control over the markup...however after three years of experiance with asp.net webforms I now understand why its better and understand you have as much control you want over the markup!  If I was starting out now, I would probably perfer the MVC Framework because back then I wouldnt have understood why webforms has been made like it has. 

    ShaneBauer:
    If you don't see the benefits, then don't use it

    I do...ive used it!! You're missing my point! 

     

    ShaneBauer:
    to tell someone why they should use a tool isn't beneficial for anyone

    Im not telling!  Im not saying dont use MVC and use webforms instead.. Im saying is it a good idea to mix markup with code? I dont mind what other people do! 

    ShaneBauer:
    saying that a certain tool is only for people that can't understand another is ridiculous.

    You have taken this out of context or I did not make my implication understandable.  I was trying to say its easier for people begining asp.net development.. there is far less to learn in terms of various server side controls etc.  This isnt to say its no an appropriate framework for experianced people either!!

    Cheers,

    David Kiff
    http://DavidKiff.co.uk

    -- "Mark As Answer" If my reply helped you --
  • Re: Code Blocks vs. Code Behind

    03-28-2008, 4:21 PM
    • Loading...
    • jbardrof
    • Joined on 03-22-2007, 11:47 PM
    • Naples FL
    • Posts 190

     

    DavidKiff:
    Ok change of mind!! I think the MVC Framework is great for people who dont understand how to use WebForms and strugle to understand the page cycle eyc!  The MVC model is much simpler to use.

    That perfectly highlights your basic opinion.  I for one love the new MVC way of handling things and I had absolutely no trouble understanding the page lifecycle. I never liked it, never liked viewstate, pages got bloated. In fact I would have to say that Webforms are great for people that don't understand how to manipulate the stateless nature of the web. Webforms injects a pseudo state into a stateless entity.  The idea of RESTful web apps and other such notions that many other frameworks employ was not followed by asp.net. Of course, its fine that MS went in a different direction, but for those of us who would rather have full control of their html, MVC is a better option.  Webforms creates a sense of security against having to understand html, while some may like that approach, it is no way a superior approach which would make MVC the lesser paradigm. 



     

    Remember if you have gotten your answer to mark your thread as answered.
  • Re: Code Blocks vs. Code Behind

    03-28-2008, 9:06 PM
    • Loading...
    • tgmdbm
    • Joined on 12-17-2007, 2:08 PM
    • Posts 639
    • ASPInsiders

    Great discussion guys.

    I have a 4 comments. please read through before flaming *wink and a smile*

    1) People tend to complain about "logic in the view" and talk about "logic vs markup". They say that "logic doesn't belong in the view", but whether you're using controls or code blocks, you're still using logic. The point is, this logic is "view logic" which absolutely belongs inside the view (whether it's hidden inside controls or visible in code blocks)

    DavidKiff:
    [GridView exmaple]

    Less lines of code!! No foreach logic within the markup!  The only advantage I can see that the MVC view has is type-safty!  If you really want complete control over you code why not use a repeater?  That is the reason they are designed!!

    You forgot the lines of code which bind the GridView to a data source. Whether you're defining your data source declaratively, or in code behind, (apart from more lines of code) you're separating it from the grid which makes it a little less discoverable. You're right in saying that the foreach isn't in the markup, but the "logic" is still there, you've just hidden it inside your GridView. This just means you need to understand what your controls are doing behind the scenes, where as "foreach" and "if" can almost be read in english.

    2) You mentioned type-safety. Absolutely! But more than that.

    a) With data binding you're performing reflection on the data source, so our "type safety" has a significant performance gain.
    b) The code is visible to refactoring tools (like Resharper, but not VS?! lol) so when you refactor your data types, Resharper can update the references in your view, but it won't touch things like Eval("el.Value").
    c) Intellisense

    3) Don't get me wrong, I'm not saying you should use code blocks everywhere. If you do, you're bound create a maintenance nightmare (I've been there). We need a little help. And for this, we have helper methods. HtmlHelper is full of neat little nuggets of html which we can just drop into our pages. We can even avoid using reflection on our data sources by passing delegates to our helper methods (I'm pretty sure this will be implemented in a future release of the framework but you can write it yourself for now). You can't exactly pass delegates to a control!

    You're still using <%%> tho, but Html.TextBox() feels more like a control. 

    4) You asked "why not use a repeater?", you can. And, assuming the MVC team haven't changed their minds, you'll be able to use <mvc: controls just like the <asp: ones you're used to. They'll output nice html but obviously won't respond to postback events etc. They will apparently be wrappers around the HtmlHelper methods (from what I heard).

    Plus you can still use your own controls and put some logic in the code behind, as long as you're careful not to expect the WebForms postback model. But a lot of people here frown on using code behind, especially since we don't have to any more.

    But as Scott Hanselman said "We've already got a Repeater, it's called "foreach"."

  • Re: Code Blocks vs. Code Behind

    03-29-2008, 1:44 AM
    • Loading...
    • Michael Carman
    • Joined on 12-04-2007, 7:24 PM
    • West Palm Beach, FL
    • Posts 5

    Yea, this is a good discussion.  I personally use a combination of inline code, HTML helpers and server controls.   For reason already mentioned in this thread (refactoring, type safey, etc..), I always use inline code when referencing the model.  But I do like to use server controls for common HTML blocks. For example, here is a some of code for a simple form.

    <form action="<%=Url.Action(new {action="SaveContact", id=ViewData.ContactId})%>" method="post" id="ContactForm">
                   
            <ui:FieldContainer ID="FirstNameCt" Label="First Name" Required="true" runat="server">                
                <input type="text" name="FirstName" value="<%= ViewData.FirstName %>" maxlength="50" size="50" />
            </ui:FieldContainer>
            
            <ui:FieldContainer ID="LastNameCt" Label="Last Name" Required="true" runat="server">
                <input type="text" name="LastName" value="<%= ViewData.LastName %>" maxlength="50" size="50" />
            </ui:FieldContainer>           
                        
            <div class="buttonContainer">
                <button type="submit"><span>Save</span></button>
            </div>                   
    </form>
    

    I am using the FieldContainer control to wrap the fields with the appropriate div's and labels.  I probably could have created a helper method like Html.FieldContainer("FirstNameCt", "First Name", true). But I found the server control easier to read.  In the end, my goal is to create code that easy to read (discoverable) and maitain. 

    To answer the original posters question, I don't see anything wrong with using code blocks for the diplay logic. Code blocks gives us type safety, the abililty to refactor, and better performance.  Can it be misused? Sure, but so can server controls. 

    On a side note, since we do not have to deal with ViewState and post backs in MVC, creating server controls is much easier :)

  • Re: Code Blocks vs. Code Behind

    03-29-2008, 7:20 AM
    • Loading...
    • DavidKiff
    • Joined on 12-07-2006, 11:07 PM
    • Hertfordshire, UK
    • Posts 1,633

    Hey,

    Good answers Michael Carman and tgmdbm.  tgmdbm I think you've changed my my opinion of inline code blocks.

    tgmdbm:
    The point is, this logic is "view logic" which absolutely belongs inside the view

    Absolutly right, however should the logic be extracted away from the mark-up?  In WebForms there is still view logic but its not mixed in the HTML its nicely placed inthe codebehind.. or abstracted away into the server controls themselves.

    Saying this you have made some really interesting advantages that seem to out weight the non-seperation of GUI logic and markup.. The perfomance gain one is rather obvious.. now you have mentioned it!  and then the light "weightness" of everything seems cool.. why have a resource eating gridview when you dont use half the features..hmm

    Thanks alot for the input this is what I was after in the first place! Big Smile

    David

    David Kiff
    http://DavidKiff.co.uk

    -- "Mark As Answer" If my reply helped you --
  • Re: Code Blocks vs. Code Behind

    03-29-2008, 10:36 AM
    • Loading...
    • tcox
    • Joined on 03-28-2008, 11:07 PM
    • Oklahoma
    • Posts 2

    I work in an agile shop. We examine the value for each piece--even separation of concerns.

    Don't do things academically. Do them because they matter and bring value.

    For a quick UI, to get feedback from the user, we'll put it ALL on the page using prototype.js.
    If the logic is ONLY about UI, that's where it belongs. That's where you develop it and test it, so maitain it there.

    If the app uses the database to the point the controller would start to look like a repository, guess what, we need a repository. 

    The value should be what drives development. Patterns are just another tool in your belt.

    If it's easy to maintain and refactor, it's the right pattern for this app--maybe not the next one.

    Don't allow a history of bad apps in code blocks steer you just because you see the reminding <%

    If it's hard to do it right, you have habitually done it wrong.
    Just write the test.
  • Re: Code Blocks vs. Code Behind

    03-29-2008, 2:59 PM
    • Loading...
    • tgmdbm
    • Joined on 12-17-2007, 2:08 PM
    • Posts 639
    • ASPInsiders

    DavidKiff:
    however should the logic be extracted away from the mark-up?
     

    This is a choice for you as a developer. As Micheal suggests it's all about readability.

    First of all, do not be afraid of code blocks, they are your friend! But if you think your code blocks aren't very readable, try putting it in a helper method. If your helper methods don't do it for you, create a control for it.

    You have so much choice. Experiment.

  • Re: Code Blocks vs. Code Behind

    03-29-2008, 3:19 PM
    • Loading...
    • srulyt
    • Joined on 02-02-2008, 6:16 PM
    • Posts 209

    I think it would be nice if the MVC team put out a few more helper methods and a few controls that would help the developers who do not want to put logic in their vies avoid it. As for those who don't mind and prefer more control over the output using inline code is fine. It is not like classic asp, as many have said, becuase it is only view logic. It is also different than asp because in the end it uses the Asp.Net pipeline and gets precompiled making it run faster and less buggy.

    I played around with the webforms view engine and i was able to add server side controls and it ran very nicely. I used a server side form and agrid view in my test and it rendered like any webforms page would. I added a button to see what the postback would od and it caused a regular MVC pattern. It seems that should one really like webforms but still want to use MVC they could be used together. This does seem to have some serious performance issues because now yoy have to run the MVC pattern and the regular pagecycle and render a control tree, but if this is not an issue in your case using server controls seemed to work fine in MVC

  • Re: Code Blocks vs. Code Behind

    04-02-2008, 10:38 AM
    • Loading...
    • superevanc
    • Joined on 02-15-2006, 9:11 PM
    • Posts 49

    I believe part of the problem is that some people find there is a smell with the ASP.NET view engine.  There are other view engines that are out there.  I haven't had a chance to try any out with ASP.NET MVC yet.  The nhaml project looks really cool and that is probably at the top of my list to try: http://andrewpeters.net/2007/12/19/introducing-nhaml-an-aspnet-mvc-view-engine/.

    I hear that nvelocity also works with asp.net mvc but I haven't seen this in action either.  I've used nvelocity with monorail and although I think the master page concept works better in the ASP.NET view engine nvelocity has a lot more readability.

    I would like to see Microsoft put some effort into a new view engine.  Trying to make use of the existing ASP.NET one is all well and good to get things going and help converts, but I find it very hard to use and maintain for MVC style apps.
     


    Filed under: , ,
  • Re: Code Blocks vs. Code Behind