views:

135

answers:

5

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?

A: 
<%=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.

Chris
+2  A: 

You can still use a normal user control. Just don't rely on viewstate and postbacks and you shouldn't have any problems.

Mattias Jakobsson
A: 

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

Raj Kaimal
A: 

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!

n8wrl
In this project, labels and literals are actually less flexible because we're using Javascript quite extensively for the UI. Should also have mentioned, we're on a slow migration path to MVC so we're trying not to rely on postbacks.
realworldcoder
@n8wrl, How is labels more flexible then <% %>?
Mattias Jakobsson
@Mattias: Because your code-behind can do more validation on the content that should in the labels. What if that content depends on some object that is NULL or otherwise invalid? Harder/messier to validate inside <% %>
n8wrl
@n8wrl, You can still do the logic in your code behind (or anywhere) and just write the value when using code blocks. No difference. I prefer code blocks as I think it looks a lot cleaner.
Mattias Jakobsson