ASP.NET - Inline vs. Code-Behind - asp.net

I realize that by asking this question, I could have started the apocalypse, but a colleague of mine uses a lot of inline coding in their aspx pages, where as I prefer using the code-behind.
Is there a right and a wrong way here?

Not unless your coding standard says otherwise.
IMO code-behind helps separation of concerns, so I prefer that, but sometimes just dealing with one file is nice too.

Code-behind is the more traditional and logical place. If it works, it works, but I can't stand doing it in the aspx.

I made the exact post a while back:
OnDataBinding vs Inline: pros, cons and overhead
I prefer the code behind. I usually have a #region area for all the databinding stuff. It allows for people skilled in HTML / CSS to tweak the HTML and all they have to know is what basic controls to use and to define the OnDataBinding event in the control's definition. They can move things around and do whatever and have no knowledge of what it actually takes to get the data into that databind as it might not be as simple as just a basic 'Eval("something");.

Well, there's inline code, and then there's inline code. If you have a script block at the top for you page_load, that's just fine. But if you're mixing a lot of bee-stings (<% %>) in with the markup, you'll eventually start to have trouble when those bee-stings don't work as you would like with other server controls.

Personally I prefer compile errors to run-time errors so I put all my logic in code behinds.
Occasionally when I just need a value to show up on the page I'll put <%=SomeValue%> but even then I much prefer to create a label and set it.

I want to make sure i understand the question - by in-line, do you mean snippets like
<a><% some.asp.net.code %></a>
or do you mean one vs. two files for each page:
page.aspx
page.aspx.cs
?
Because I am NOT a fan of what I call the 'embedded' code in the first example but I DO prefer code and markup in the same file with a < script runat="server">

There is no right/wrong with either of this.
You can write some code inline & some of it should be written in code-behind. It can't be absolute. Depends on how readable/maintainable it becomes when you write it on the other side.
EDIT: As it is said, write code for human & incidentally for the compiler.

I tend to use the code-behind since it is the only way for WPF and I try to stay consistant and it feels more natural. But thats subjective.

Related

Is it bad to use runat="server" on <tr>?

I'm supporting an application that uses runat="server" all over the place to show/hide table rows.
For example, in places where there are dependent DropDownLists, the row with the child ddl will be hidden until a value us chosen in the parent ddl.
Is that a bad practice? Is there a better way to do this?
I use runat="server" anytime I need it. So I think you can use it too. :-)
I think that's absolutely terrible practice. First of all you do not need to make the trip to the server to hide and show controls, unless you need new data.
Second, any decent javascript framework will allow you to hide show controls based on the control's id, class name, or whatever css selector. Moreover using a javascript post/get to a generic handler will give you the data that you need without the postback.
I'd suggest using JQuery, or some other alternative.
It depends on how much you care about performance. Anything that is marked with runat="server" goes through more processing than just client side tags.
Personally, I've used them before. Especially in the situation where a table cell or table row is relying on data from the server. You can use Javascript or JQuery with a hidden field but you still have to hit the server for the hidden field, so it doesn't buy much.
It's not bad to use runat="server" with standard HTML controls. Often you'll find the use of PlaceHolders to show and hide content on pages, or in ASP.NET MVC you might see the use of inline code blocks such as <% ... %> within the views. On it's own and not in consideration of other design aspects, it's neither good nor bad.
That's what I do to hide the row containing other server controls. The other options are to use a asp:panel or other container, but that will add more HTML without any gain.
I don't think it's necessarily bad practice. I've done the very same thing plenty of times. I think it's mainly personal preference.
Not at all. ASP.NET supports making any html tag run on the server side. Your alternative is to wrap the tag in a Panel, and hide or show that. If you're not looking for the extra functionality or want to control the output yourself, making an html tag run on the server isn't a problem.

Why is this consider bad practice? or is it? (ASP.Net)

Would this code be considered bad practice:
<div id="sidebar">
<% =DisplayMeetings(12) %>
</div>
This is a snippet of code from the default.aspx of a small web app I have worked on. It works perfectly well, runs very fast, but as always, I am aware of the fact that just because it works, doesn't mean it is OK.
Basically, the DisplayMeetings subroutine outputs a bunch of formatted HTML (an unordered list actually), with no formatting, just the requisite html, and then my CSS performs all the necessary formatting.
The data for generating the list comes from an SQL server database (the parameter controls how many rows to return) and I am using stored procedures and datareader for fast access. This keeps my front-end extraordinary simple and clean, imho, and lets me do all the work in VB or C# in a separate module.
I could of course use a databound repeater (and probably 6 or more other methods) of accomplishing the same thing, but are they any better? Other than loosing the design-time features of VS2010?
The only thing "wrong" with your approach is that it mixes code and display, which you typically want to avoid wherever possible. If you have to have a procedurally generated portion of HTML (because it's just that difficult to do with controls, or whatever), create a control responsible for generating that HTML and embed it in the larger page/control that contains it.
is the "wrong" part, that the subroutine is returning HTML, or is it that I have a code-snippet executed from within the HTML markup?
Both, in a way. And also neither.
There's nothing directly "wrong" with using <%= foo %>; if there were, it wouldn't be part of the framework. What's "wrong" with it is that it sets up a two-way dependency that you don't necessarily want. Your HTML markup is dependent on and has to know about the code-behind. It has to call the method, which in turn is dedicated to the markup and nothing else. If you want to make changes to your output, you may have to change the method, the markup, or both.
What I'm trying to say is that what you're doing makes your code less maintainable, less flexible to modify the next time you have to open the hood.
If it's the only way to solve a problem, then it's the only way, and there's nothing wrong with that. But it's something that should be avoided, in general, if possible.
How would I have done it? That depends on the situation, frankly. If I could have used a standard component with databinding, I'd have done that. That is always preferred. If the HTML was just too complex to use a component, I'd use a Literal control as a placeholder for the markup, and generate the markup in a separate component--likely a User Control.
The point is that the markup knows nothing about the method used to generate the other markup, it just says "something goes here" and relies on its code-behind to handle deciding which markup to put in there.
It's not something I'd do. I'm not a fan of using <%= %> in Webforms. Sadly, it's also common practice.
What I'd probably do instead is a build a user control to represent the markup I wanted and put that on the form. This has the advantages of making the element more re-usable, testable, and gives you more control over where in the page life cycle the code is called.
A databound repeater can make it somewhat simpler to modify your html when you need to change the layout. It is also nice if you have separate people who work on html vs people who work on the server side code.
My usual rule is to use a repeater for any even slightly complex html. And I do not call methods from my aspx/ascx file - I only insert the values of a protected string variable which I have populated in the code. However, these are personal preferences, and I don't see anything really wrong with what you are doing.
Your code (without seeing it) will likely be faster than a repeater, since there is no data binding involved, but it probably wouldn't be a huge thing unless the page is very, very popular.

Alternatives to ASCX User Control without a server-side form?

I've got an ASP.NET 3.5 Web Forms application in which a large chunk of code needs to be duplicated between a few different pages. Sounds like the ideal candidate for a user-control right? Problem is, this cannot be contained within a <form runat="server"> because it contains a client-side form of it's own.
There are no runat=server controls or postbacks or anything that really need that webform - think of it just as a chunk of HTML with a few basic <% %> tags. I'd just want to set a property on the control when it's loaded, so that it knows what to output. This is purely an exercise to make the code easier to maintain.
Before I resort to using an oldskool <!--#include-->, is there some better way of doing this?
You can still use a normal user control. Just don't rely on viewstate and postbacks and you shouldn't have any problems.
<%=Response.Write(File.ReadAllText(Server.MapPath("~/includes/filename.ext")))%>
Something along those lines, anyway.
Edit: Same functionality as a server side include, but if I'm not mistaken, enabling the SSI syntax requires an IIS change, where as this wouldn't.
Edit 2: I didn't see the note that your include contains asp.net code. This would obviously only work for client side code only. My mistake.
You can have as many form controls as you want but only one can have runat="server".
Some other techniques:
http://webproject.scottgu.com/CSharp/UserControls/UserControls.aspx
http://weblogs.asp.net/scottgu/archive/2005/08/28/423888.aspx
I'd still make it a control. The <% %> stuff could be labels/literals for more flexibility, and as soon as you get done saying there are no postbacks needed, you'll need them. Best to set up the other pages to include it as a control now for easier changes later. Heck - you could even take advantage control-level caching!

ServerControl versus UserControl

I'd like to hear some reasons for using a ServerControl opposed to a UserControl. I've found that I probably overuse UserControls.
My list looks something like this:
Pro UserControl
Easily modified. Need to add a class attribute to an element, hack it out in html.
Quick and easy to create initial view. Everyone can write simple html right?
Pro ServerControl
Performance. No html parsing.
Flexibility. Control rendering down to a gnat's behind.
Reusability. Compile it and stick it in the GAC for later use. Or, sell it.
Anything that I'm missing?
The following two advantages of server controls come to mind:
support for inheritance (because the actual user control at runtime inherits from your code behind, you can't inherit from it anymore)
detailed control over the tag's parsing (should nested tags be treated as child controls or properties, etc.)
support for control adapters (declarative, e.g. in a .browsers file)
support for tag mapping (if you're making your own controls that's often very useful though)
However, user controls do have an additional edge because they're templated:
support for databinding expressions
One other consideration is whether you want visual studio designer support at the time you're building the control or at the time you're using the control on the page. It really irks me that you only get one or the other, but not both.
Performance. No html parsing
I wouldn't expect that to be much of a runtime difference - the .ascx should get compiled on first use as well. Perhaps there's some slight overhead saved by not checking the file for modifications - but I can't think of much else.

Codebehind and inline on same page in ASP.NET?

In ASP.NET, is it possible to use both code behind and inline on the same page? I want to add some inline code that's related to the UI of the page, the reason to make it inline is to make it easy to modify as it outputs some HTML which is why I don't want to add it in the code behind, is this possible in ASP.NET?
Edit: I'm sorry, obviously my question wasn't very clear, what I meant is using a script block with runat="server", this is what I meant by inline code.
Thanks
Yes, you can use inline code just like in classic asp. You can use 'this' or 'me' to get to the code behind fields, methods, etc.
Yes, that will work, make sure the code behind class is declared as a partial class, which is the default these days anyway. Don't think it would work in 1 or 1.1

Resources