views:

52

answers:

4

How can I insert code into a page in ASP.Net from a seperate source file?

Say I have:

   <% 
         Response.Write("hello world");
   %>

How can I make it something like:

   <% include(helloworld.cs) %>

I know how it work sin the header with the <%@ and CodeFile= but I can't make it work for different spots of code. Is there a way ASP.Net handles this? I've tried googling but not sure what to search for.

+1  A: 

You can't shouldn't.

Instead, you should create a User Control.

SLaks
This is not correct. You can use old-style server-side includes. I agree that you *shouldn't* do it, and should use User Controls instead, though.
Andrew Barber
@Andrew: Not with server-side code in them.
SLaks
Absolutely yes, SLaks; with Server-side code in them. The content of the included file runs exactly as if you had typed it in the source file that references it.
Andrew Barber
@Andrew: What are you talking about? Can you provide a link?
SLaks
I've just done it myself with a file named "inc.inc" and included it in an ASP.NET 4.0 page. the inc.inc file used a server-side tag like so: `<%= DateTime.Now%>` and it worked perfectly.
Andrew Barber
@Andrew: [I take that back](http://msdn.microsoft.com/en-us/library/3207d0e3%28v=VS.100%29.aspx). I never knew that; thanks.
SLaks
+1  A: 

you could create a class library and add a reference to the library.

link that may help:

http://support.microsoft.com/kb/306575

Orbit
I too think a Object Oriented approach would be appropriate :)
Ranhiru Cooray
That link is irrelevant.
SLaks
Creating a class library just to include some boilerplate UI markup seems like overkill.
Andrew Barber
+1  A: 

Another option not mentioned yet is to use ASP.NET Master Pages. This is useful to have a consistent look and feel (and code behind) in the master page which extends to the child pages.

Ahmad Mageed
+1  A: 

You can use old-style Server-Side include tags like so:

<!-- #include virtual="/inc.inc" -->

But I do not recommend it. You should use User Controls instead; they give you more capability, and do not potentially expose server-side code if someone should happen to try to request them directly.

If you nevertheless decide to use includes like that, note that the content of the file is included in the ASPX/ASCX source code just as if you had typed it right in the main source file itself.

Andrew Barber