Why is this consider bad practice? or is it? (ASP.Net) - 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.

Related

Get value form elements inside div with only ASP.NET

I'm newbie in ASP.NET and i think that my question is quite simple, but I'm not getting success in my searches through google or even stackoverflow.
I have a asp.net method (vb.net) that loads a entire html page inside a div.
Doing searches, i discovered that it can be like this:
On .aspx page:
<div id="content"></div>
On .vb codebehind:
Private sub LoadContent()
content.InnerHtml = MyDLL.LoadFromDatabase.Value.ToString()
End Sub
So, nothing special until here.
But, if consider that the html code loaded from database has form elements like <input id="name" type="text">, my problem starts...
On page postback these don't keep the values as <asp:TextBox> created natively on code, does.
And the other thing that I want is a way to retrieve the value from them to work on codebehind, like: myvar = content.Controls("name").Value
At least, is there a way to solve my problem?
Sorry for my bad english, and thanks so much.
CRice is right. If you want the viewstate to persist through postback you need to create the controls server-side.
Careful though: I've had bad experience with dynamically created controls on Asp.Net, specifically when trying to bind events to them. Not only would you have to use delegates and events (a hard topic for a newbie), also when I tried it a few years ago I just couldn't get it to work, no matter what.
If you're going for dynamic created controls, make sure it's worth the effort, because it WILL be an effort, now and in the future when you would like to maintain and add expand. A rule of thumb is that dynamic mechanisms are always harder to maintain than static ones, but they provide more flexibility.
Having that said, if you're still going for dynamic html loading, be aware that better solutions exist, though they require different architectures: client side frameworks (best is angluar.js) provide dynamic loading of "modules" (and much more), which is what you want. On the server side, asp.net MVC with its Razor view engine, partial views etc., is better suited for dynamic html generation.
Back to your original question,are you sure you need a full postback? What about a nice neat Ajax call to a web service? Can get the job done in many cases without reloading the whole page. I guess using jquery's $.ajax syntax and creating a simple .asmx web service will be easiest for you.
Last but not least, why use vb.net instead of c#? It sucks man. Give it up while you still can.

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.

ASP.NET - Inline vs. Code-Behind

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.

Which is better to initialize HTML control values: Javascript or inline server tags?

Which is better/more maintainable, using Javascript to initialize the values of the different HTML controls or writing inline <% %> tags?
The current page I am writing has many HTML controls and I'm afreaid that putting inline ASP would make it too unmaintainable.
Well... using JS to populate the controls with values will make the whole solution useless in JS-free environments. This is not what the webdev community calls unobtrussive.
As you donĀ“t define better any better (!) I would say go for the inline rendering.
If you really have millions (I really doubt this number) of HTML Controls in your page I would say you need to get back to the drawing board and re-architect the solution.
You are going to have the same problem regardless of the method: maintainability.
I have some legacy forms that need to remember some fields between calls, so I have a lot of code that might be a little ugly, but if you stick to a standard, doesn't get too messy.
<label for="email<%=i%>">E-Mail<% if required then %> (*)<% end if %>:</label>
<input name="email<%=i%>" id="email<%=i%>" type="text" value="<%=Trim(request.form("email"&i))%>" />
The problem is that it involves a lot of copy paste when having to add a new control. You could make a function to build it and keep the code duplication to a minimum.
<%= BuildHTMLInputControl("email"&i, "text", "E-Mail", true) %>
' Response: <label for="email1">E-Mail (*):</label><input name="email1" id="email1" type="text" value="Previous Value" />
I haven't done something like this, because it hasn't been a concern yet in the small forms that I've done this.
The advantage of this is that the fields are populated onload, there is no flashing of content and you are really friendly to non-Javascript users, something that you should be.
The only difference would be that with javascript youd have a lot of document.getElementById() at the beggining (or rather end) of the document, that increases the HTML file size (which might be a concern) and could not populate the fields instantly.
If you've really got loads and loads of HTML controls in an ASP.Net page, you might have to rethink your design. Why aren't you using server controls?
However, you can always use the runtat="server" attribute on HTML elements to effectively turn them into server-side controls. You can then work with them in much the same way as ASP.Net controls. You may want to watch out for extra Viewstate being added, though.
What is better/more maintainable,
using Javascript to initialize the
values of the different HTML controls
or writing inline <% %> tags?
I wouldn't do it either way. That sounds like old-style ASP, or maybe PHP or JSP-type logic.
The ASP.NET model is to use controls on the page, and then to set the values of those controls either from code-behind or in-line code, possibly using some type of data binding. Separating the display logic from the data is much, much easier to maintain.

Resources