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

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!

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.

Is it a good idea to use plain HTML instead of ASPX

I'm developing an ASP.NET website. Sometimes some modules contain so few content that I present them inside a jQUeryUI dialog and communicate with the server via AJAX. I keep those contents inside a separate file and load them to a jQueryUI dialog according to the appropriate module.I was wondering if it's a good idea to have that content as a plain HTML elements instead of asp ones. Somehow I thought maybe this would reduce the overhead the conversion from asp elements to html elements can cause.
I'd allways go with the aspx Page, because a dynamic Page is more work at the beginning but in the end it almost ever saves time.
Specially when your not sure of the content that will be shown there, it is better.
And for the one reason i do it, is to have everything the same.
One style one way to code.
I'd say this is probably premature optimization. The overhead of an aspx page is in almost all cases negligible. I believe it's more likely that you will some day need to put dynamic things in that page, in which case you would have to convert the html file to an aspx, and change the url for your ajax dialog - which will cost time/money.
If you have aspx pages, or ascs user controls that you do not actually use/run any code, you can set the AutoEventWireup the EnableViewState, and maybe the EnableSessionState to false and stop the calling of the PageLoad and the rest functions and reduce the overhead. So on top of the controls you declare:
<%# Control AutoEventWireup="false" EnableViewState="false" ...
or for page:
<%# Page AutoEventWireup="false" EnableViewState="false" EnableSessionState="false" ...
The disable of the session is let the pages loads in parallel, the disable of the EnableViewState is reduce the size, the AutoEventWireup is reduce the callback hooks and calls.
In general you can use what ever you wish - if your pages can work, but if you like to keep it robust and easy to change or update, or add new functionality in the future, then use dynamic aspx pages.
Similar question: Master page and performance

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.

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.

Register Startup Script Control

I am looking to make a web control where I can register client startup scripts inline with my aspx because I hate registering in the codebehind!
An example of what I have so far:
<Ben:StartupScript runat="server">
var form = document.getElementById("<% =form1.ClientID %>");
</Ben:StartupScript>
Currently, I am overriding the OnPreRender method of the control, rendering the contents of the control to a string and then manually registering that string as a startup script using ClientScript.RegisterStartupScript on the Page. I also override the Render method in order not to render the control. I should also note that I have the ParseChildren attribute set to false and the PersistChildren attribute set to true.
All seems to be working well, but my control allows other web controls inside it (such as Button). Apart from being unintuitive, this can result in runtime errors. I would love to be able to clear the controls but this is impossible given the <% ... %> code block.
So, is it possible to prevent developers from embedding child controls whilst still allowing code blocks?
Also, is this idea any good or is it fundamentally flawed? Lol.
Thanks a bunch,
Ben
it sounds like a good idea, but if you spend too much time fighting the inherited/default behaviors then it may be more trouble than it's worth
if this is a one-shot issue, a cheap-hack solution is to just directly embed your scripts in the header of a master page ;-)
on the other hand, allowing developers to embed their own scripts as children of your web control might be useful
If you are using master pages, add another control in your section. That way you can easily add css/js to your headers in your child pages.
ClientScript.RegisterScript is mostly for user/server controls,

Resources